Search completed in 1.22 seconds.
Flow Layout and Overflow - CSS: Cascading Style Sheets
when there is more content than can fit into a container, an overf
low situation occurs. understanding how overf
low behaves is important in dealing with any element with a constrained size in css. this guide explains how overf
low works when working with normal f
low. what is overf
low? ...
... when there is more content than can fit into a container, an overf
low situation occurs. understanding how overf
low behaves is important in dealing with any element with a constrained size in css. this guide explains how overf
low works when working with normal f
low. what is overf
low? ...
.... understanding how overf
low behaves is important in dealing with any element with a constrained size in css. this guide explains how overf
low works when working with normal f
low. what is overf
low? ...
...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 f
low. all elements that are in f
low, will be laid out using this method. in the fol
lowing 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 f
low. 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 f
low. 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 f
low. 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-al
low-origin’ not al
lowed what went wrong? more than one access-control-al
low-origin header was sent by the server. this isn't al
lowed. if you have access to the server you can change your implementation to echo back an origin in the access-control-al
low-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 ref
low table frames table ref
low intro to paginated ref
low table paginated ref
low review of ref
low ref
low 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 ref
low command with itself as the target. content is inserted, appended, or deleted through the dom. the container posts a dirty ref
low 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 ref
low command with itself as the target. content is inserted, appended, or deleted through the dom. the container posts a dirty ref
low command with itself as the target. style changes through the dom - javascript, browser change font (ctrl+/-), a preference changes, etc. review of ref
low ref
low starts with pres shell which ref
lows the ref
low root (usually the viewport frame), which ref
lows it children, etc. ususally it starts when the pres shell processes its queue of ref
low commands. ...
...container posts a dirty ref
low command with itself as the target. style changes through the dom - javascript, browser change font (ctrl+/-), a preference changes, etc. review of ref
low ref
low starts with pres shell which ref
lows the ref
low root (usually the viewport frame), which ref
lows it children, etc. ususally it starts when the pres shell processes its queue of ref
low commands. the ref
lower positions ref
lowee (if it can) before actually ref
lowing 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 f
low based layout model, meaning that most of the time it is possible to compute the geometry in a single pass. elements later "in the f
low" typically do not affect the geometry of elements that are earlier "in the f
low", 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
the overf
low css shorthand property sets the desired behavior for an element's overf
low — 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. ...
......
... overf
low-x overf
low-y syntax /* keyword values */ overf
low: visible; overf
low: hidden; overf
low: clip; overf
low: scroll; overf
low: auto; overf
low: hidden visible; /* global values */ overf
low: inherit; overf
low: initial; overf
low: unset; the overf
low property is specified as one or two keywords chosen from the list of values be
low. if two keywords are specified, the first applies to overf
low-x and the second to overf
low-y. otherwise, both overf
low-x and overf
low-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 al
lowing the user to scroll (such as by dragging or using a scroll wheel) is al
lowed. the content ...
...And 15 more matches
text-overflow - CSS: Cascading Style Sheets
the text-overf
low css property sets how hidden overf
low 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-overf
low property doesn't force an overf
low to occur. to make text overf
low its container you have to set other css properties: overf
low and white-space. for example: overf
low: hidden; white-space: nowrap; the text-overf
low property only affects content that is overf
lowing a block container element in its inline progression direction (not text overf
lowing at the bottom of a box, for example). synt...
...sn't force an overf
low to occur. to make text overf
low its container you have to set other css properties: overf
low and white-space. for example: overf
low: hidden; white-space: nowrap; the text-overf
low property only affects content that is overf
lowing a block container element in its inline progression direction (not text overf
lowing at the bottom of a box, for example). syntax the text-overf
low property may be specified using one or two values. if one value is given, it specifies overf
low 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 overf
low 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-overf
low as an empty string, if that is supported in your target browsers: text-overf
low: '';. 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 overf
low is what happens when there is too much content to fit in a container. in this guide you will learn what overf
low 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 overf
low and how to manage it. what is overf
low? 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). overf
low happens when there is too much content to fit in a box. css provides various tools to manage overf
low. 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 ref
low can be logged with the debug capabilities implemented in nsframe.cpp. it provides the fol
lowing information for each frame at the start of its ref
low ref
low reason available width, available height computed width, computed height the previous and the next frame in f
low and a count number. when the frame's ref
low is finished the fol
lowing information is displayed : ref
low metric (desired) width, height max. element width maximum width frame status overf
low 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 ref
low_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
ref
low the most efficient tool to claim that html-table code is the victim and not the source of layout bugs is a frame ref
low debug log. look there especially how the maxelementsize (mes) and desired size are propagated. block ref
low another way to debug the ref
low process is implemented inside nsblockframe.cpp. ...
... ref
low the most efficient tool to claim that html-table code is the victim and not the source of layout bugs is a frame ref
low debug log. look there especially how the maxelementsize (mes) and desired size are propagated. block ref
low another way to debug the ref
low 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 ref
low debug log. look there especially how the maxelementsize (mes) and desired size are propagated. block ref
low another way to debug the ref
low 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 f
low 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 fol
lows: 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 overf
low-x css property sets what shows when content overf
lows a block-level element's left and right edges. this may be nothing, a scroll bar, or the overf
low 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 */ overf
low-x: visible; overf
low-x: hidden; overf
low-x: clip; overf
low-x: scroll; overf
low-x: auto; /* global values */ overf
low-x: inherit; overf
low-x: initial; overf
low-x: unset; the overf
low-x property is specified as a single keyword chosen from the list of values be
low. 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: f
low-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 overf
lowing 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 f
low layout and writing modes. elements participating in a block formatting context block elements in a horizontal writing mode such as english, layout vertically, one be
low 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 be
low 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-al
low-headers: <header-name>[, <header-name>]* access-control-al
low-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.effectal
lowed property specifies the effect that is al
lowed 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 effectal
lowed 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 effectal
lowed may be used to determine which effect is permitted. assigning a value to effectal
lowed in events other than dragstart has no effect. syntax datatransfer.effectal
lowed; values a domstring representing the drag operation that is al
lowed. 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
the flex-f
low 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. ...
...-f
low 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 f
lowed 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-f
low: row; grid-auto-f
low: column; grid-auto-f
low: dense; grid-auto-f
low: row dense; grid-auto-f
low: column dense; /* global values */ grid-auto-f
low: inherit; grid-auto-f
low: initial; grid-auto-f
low: 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 al
lowed. 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 fol
lowing 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 fol
lowing 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 f
low 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 f
low 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 f
low 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 f
low 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 f
low 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 f
low 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 f
low 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 f
low direction is the direction in which boxes, for example paragraphs, stack in that writing mode. the css writing-mode property controls the block f
low 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 overf
low-y css property sets what shows when content overf
lows a block-level element's top and bottom edges. this may be nothing, a scroll bar, or the overf
low 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 */ overf
low-y: visible; overf
low-y: hidden; overf
low-y: clip; overf
low-y: scroll; overf
low-y: auto; /* global values */ overf
low-y: inherit; overf
low-y: initial; overf
low-y: unset; the overf
low-y property is specified as a single keyword chosen from the list of values be
low. ...
... 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: f
low-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 overf
lowing 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 fel
lowship program is closed. we are not accepting applications. this page is a historical archive, originally hosted at /fel
lowship, and was localized. more information: mdn/developerfel
lowship wiki page. announcing the mdn fel
lows! blog post, may 14 2015. mdn fel
lows successfully oriented blog post, july 6 2015. mdn fel
lows: what they did & what’s next blog post, september 23, 2015. 2015 mdn fel
lowship program launching in q1 2015, the mozilla developer fel
lowship 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 fel
low 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 al
low 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 f
low, 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 f
low, 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 f
low, 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 f
low, 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 f
low, or removing them from it altogether. starting with a solid, well-structured document that is readable in normal f
low 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 f
low 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 fol
lowing 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 fol
lowing type: exception description dataerror the value parameter passed was not a valid key. example the fol
lowing 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 f
low, or f
low layout, is the way that block and inline elements are displayed on a page before any changes are made to their layout. the f
low 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 f
low it works independently. in normal f
low, 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 fol
lowing 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
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 fol
lowing 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 fol
lowing 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 overf
low module contains the features of css relating to scrollable overf
low handling in visual media. in css overf
low happens when the content of a box extends past one or more of the box's edges. ink overf
low and scrollable overf
low there are two types of overf
low that you might encounter in css. the first is described as ink overf
low. this is the overf
low of painting effects which do not affect layout or otherwise extend the scrollable overf
low region, such as box shadows, border images, text decoration, overhanging glyphs, outlines, etc. the overf
low that we sometimes need to manage in css is described as scrollable overf
low. 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 overf
low-wrap css property applies to inline elements, setting whether the browser should insert line breaks within an otherwise unbreakable string to prevent text from overf
lowing 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, overf
low-wrap will only create a break if an entire word cannot be placed on its own line without overf
lowing. 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 overf
low-wrap, with word-wrap being an alias. ...
... contrast to word-break, overf
low-wrap will only create a break if an entire word cannot be placed on its own line without overf
lowing. 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 overf
low-wrap, with word-wrap being an alias. syntax /* keyword values */ overf
low-wrap: normal; overf
low-wrap: break-word; overf
low-wrap: anywhere; /* global values */ overf
low-wrap: inherit; overf
low-wrap: initial; overf
low-wrap: unset; the overf
low-wrap property is specified as a single keyword chosen from the list of values be
low. 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 overf
low-clip-box css property specifies relative to which box the clipping happens when there is an overf
low. ...
...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 overf
low-clip-box css property specifies relative to which box the clipping happens when there is an overf
low. it is short hand for the overf
low-clip-box-inline and overf
low-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 overf
low-clip-box css property specifies relative to which box the clipping happens when there is an overf
low. it is short hand for the overf
low-clip-box-inline and overf
low-clip-box-block properties. /* keyword values */ overf
low-clip-box: padding-box; overf
low-clip-box: content-box; /* two values */ overf
low-clip-box: padding-box content-box; overf
low-clip-box: content-box content-box; /* global values */ overf
low-clip-box: inherit; overf
low-clip-box: initial; overf
low-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 al
lowcredentials, it is used to filter out credentials. syntax al
lowcredentials = publickeycredentialrequestoptions.al
lowcredentials value an array whose elements are objects with the fol
lowing 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 overf
low, both inside the column boxes and in situations where there is more content than will fit into the container. overf
low inside column boxes an overf
low 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 overf
low into the next column, rather than be clipped by the column box. you can see an example of this be
low, 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 be
low, 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 overf
lowing 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 overf
low 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 overf
low in the inline direction. on the web this means that you will get a horizontal scrollbar. the example be
low shows this overf
low behaviour. ...
...And 3 more matches
Reason: CORS header 'Access-Control-Allow-Origin' does not match 'xyz' - HTTP
reason reason: cors header 'access-control-al
low-origin' does not match 'xyz' what went wrong? ...
... reason reason: cors header 'access-control-al
low-origin' does not match 'xyz' what went wrong? ...
... reason reason: cors header 'access-control-al
low-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-al
low-origin' missing what went wrong? the response to the cors request is missing the required access-control-al
low-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-al
low-origin header's value. for example, to al
low a site at https://amazing.site to access the resource using cors, the header should be: access-control-al
low-origin: https://amazing.site you can also configure a site to al
low 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 al
low 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-al
low-origin: * warning: using the wildcard to al
low 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-al
low-origin: * warning: using the wildcard to al
low all sites to access a private api is a bad idea. to al
low 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-al
low-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 al
lowed 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 al
lowed in function with default parameter syntaxerror: "use strict" not al
lowed in function with rest parameter syntaxerror: "use strict" not al
lowed 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 al
lowed in function with rest parameter syntaxerror: "use strict" not al
lowed 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 al
lowed 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 overf
low 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, overf
low 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-f
low 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 f
low content can f
low on all sides of the exclusion. start inline f
low 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 f
low 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 f
low content can f
low on all sides of the exclusion. start inline f
low 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 f
low 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 f
low 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 f
low 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 f
low 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-f
low property makes an element an exclusion element when it has a computed value other than auto. ...
...And 2 more matches
RTCDataChannel.bufferedAmountLowThreshold - Web APIs
the rtcdatachannel property bufferedamount
lowthreshold 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 be
low this value, a bufferedamount
low 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 onbufferedamount
low 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 onbufferedamount
low 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. bufferedamount
low events are not fired after the data channel is closed. ...
...fferedamount
low 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. bufferedamount
low 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-f
lowfrom property specifies the id of the previous element in an alternative reading order, al
lowing 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-f
lowfrom property specifies the id of the previous element in an alternative reading order, al
lowing 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-f
lowto property. this proprietary property is specific to internet explorer and microsoft edge. syntax x-ms-aria-f
lowfrom="elementid"; value the x-ms-aria-f
lowfrom property value uses an id selector to define which previous element the reading order will f
low 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 al
lows 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 overf
lows. scrollbar "traditional" scrollbars are displayed if the element's content overf
lows. "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 overf
lows. 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 overf
low in css. note: you can try out solutions in the interactive editors be
low, 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 overf
lowing 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 overf
low. test by removing some of the text from the html, that if there is only a small amount of text that does not overf
low, no scrollbar appears. ...
...ther help section at the bottom of this page. task one the content is overf
lowing 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 overf
low. test by removing some of the text from the html, that if there is only a small amount of text that does not overf
low, no scrollbar appears. try updating the live code be
low 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 overf
lows 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 overf
low 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 overf
low event is fired when an element has been overf
lowed by its content or has been rendered for the first time in this state (only works for elements styled with overf
low != visible). it is a proprietary event specific to gecko (firefox). ...
...e first time in this state (only works for elements styled with overf
low != visible). it is a proprietary event specific to gecko (firefox). ...
...ific to gecko (firefox). ...
...idth: 20px; height: 20px; background: #000; padding: 5px; overf
low: 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("overf
low", function( event ) { console.log( event ); }, false); wrapper.addeventlistener("underf
low", 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 underf
low event, which is specific to firefox, is fired when an element is no longer overf
lowed by its content. this only works for elements for which overf
low is not set to visible. the counterpart overf
low event is fired when overf
low occurs. ...
...ontent. this only works for elements for which overf
low is not set to visible. the counterpart overf
low event is fired when overf
low occurs. ...
...ed when overf
low occurs. ...
...idth: 20px; height: 20px; background: #000; padding: 5px; overf
low: 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("overf
low", function( event ) { console.log( event ); }, false); wrapper.addeventlistener("underf
low", 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-al
low-methods’ what went wrong? ...
... reason reason: invalid token ‘xyz’ in cors header ‘access-control-al
low-methods’ what went wrong? ...
... reason reason: invalid token ‘xyz’ in cors header ‘access-control-al
low-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-al
low-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 al
lowevents 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 al
lowevents 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 al
lowevents 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 al
lowevents attribute is handled in a different way. instead, the al
lowevents may be set to true on a descendant instead. this does the same thing in that it al
lows events to be targeted normally, but al
lows this to be different for each descendant. ...
... and the popup datepicker, mouse events are also retargeted to the element itself. however, the al
lowevents attribute is handled in a different way. instead, the al
lowevents may be set to true on a descendant instead. this does the same thing in that it al
lows events to be targeted normally, but al
lows this to be different for each descendant. this behavior is used for menus, for instance, to al
low 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 al
lowevents 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 s
low 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 s
low 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 s
lowly increases the volume of information diffused until the network's maximum capacity is found. to implement tcp s
low 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 s
low start threshold (ssthresh) determines the (de)activation of s
low start. when a new c...
...a source can transmit over the network before receiving an acknowledgment (ack). the s
low start threshold (ssthresh) determines the (de)activation of s
low 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. s
low 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 s
lows 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 f
low 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 al
lowsfeature() 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 al
lowed in the specified context (or the default context if no context is specified). syntax const al
lowed = featurepolicy.al
lowsfeature(<feature>) or const al
lowed = featurepolicy.al
lowsfeature(<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 al
lowed. ...
...x const al
lowed = featurepolicy.al
lowsfeature(<feature>) or const al
lowed = featurepolicy.al
lowsfeature(<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 al
lowed. example the fol
lowing example queries whether or not the document is al
lowed 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 al
lowed. example the fol
lowing example queries whether or not the document is al
lowed 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 al
lowed = featurepolicy.al
lowsfeature("camera") if (al
lowed){ console.log("fp al
lows camera.") } else { console.log("fp does not al
lows camera.") } specifications specification status comment feature policythe definition of 'al
lowsfeature' in that specification. editor's draft initial definition. ...
FeaturePolicy.getAllowlistForFeature() - Web APIs
the getal
lowlistforfeature() method of the featurepolicy al
lows query of the al
low list for a specific feature for the current feature policy. syntax const al
lowlist = featurepolicy.getal
lowlistforfeature(<feature>) parameter feature name a specific feature name must be specified. return value an al
low 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 al
lowed to use the feature. example the fol
lowin example prints all the origins that are al
lowed 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 fol
lowin example prints all the origins that are al
lowed 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 al
lowlist = featurepolicy.getal
lowlistforfeature("camera") for (const origin of al
lowlist){ console.log(origin) } specification specification status comment feature policythe definition of 'getal
lowlistforfeature' 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.onbufferedamount
low property is an eventhandler which specifies a function the browser calls when the bufferedamount
low 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 be
low the threshold specified by the channel's bufferedamount
lowthreshold. see buffering in using webrtc data channels to learn more about how to work with the data channel buffer. syntax rtcdatachannel.onbufferedamount
low = function; value a function which the browser will call to handle the bufferedamount
low 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.onbufferedamount
low = function; value a function which the browser will call to handle the bufferedamount
low 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 bufferedamount
low 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 bufferedamount
low 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.onbufferedamount
low = 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.onbufferedamount
low' 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 rangeoverf
low property will be true. given the fol
lowing: <input type="number" min="20" max="40" step="2"/> if value > 40, rangeoverf
low 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.rangeoverf
low' in that specification. living standa...
... min="20" max="40" step="2"/> if value > 40, rangeoverf
low 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.rangeoverf
low' in that specification. living standard html 5.1the definition of 'validitystate.rangeoverf
low' in that specification. recommendation html5the definition of 'validitystate.rangeoverf
low' 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 rangeunderf
low property will be true. given the fol
lowing: <input type="number" min="20" max="40" step="2"/> if value < 20, rangeunderf
low 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.rangeunderf
low' in that specification. living stan...
...n="20" max="40" step="2"/> if value < 20, rangeunderf
low 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.rangeunderf
low' in that specification. living standard html 5.1the definition of 'validitystate.rangeunderf
low' in that specification. recommendation html5the definition of 'validitystate.rangeunderf
low' 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 msregionoverf
low read-only property determines if content fully fits into the region or not. this proprietary property is specific to internet explorer. syntax string = object.msregionoverf
low values type:domstring overf
low: the region element's content overf
lows the region's content box. note that the region's overf
low property value can be used to control the visibility of the overf
lowing 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.msregionoverf
low values type:domstring overf
low: the region element's content overf
lows the region's content box. note that the region's overf
low property value can be used to control the visibility of the overf
lowing 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 f
low. fit: the region element's content fits into the region's content box. it does not overf
low. if the region is the last one in the region chain, it means that the content fits without overf
lowing. if the region is not the last one in the region chain, that means the named f
low 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 overf
low. if the region is the last one in the region chain, it means that the content fits without overf
lowing. if the region is not the last one in the region chain, that means the named f
low 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 f
low (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 f
low was fitted in regions with a
lower content-order value. undefined: the element is not a region. when the region is an actual element, msregionoverf
low 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 */ overf
low-anchor: auto; overf
low-anchor: none; /* global values */ overf
low-anchor: inherit; overf
low-anchor: initial; overf
low-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 overf
low-anchor property. body { overf
low-anchor: none; } specifications specification status comment css scroll anchoring module level 1the definition of 'overf
low-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-al
low-methods’ what went wrong? ...
... reason reason: did not find method in cors header ‘access-control-al
low-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-al
low-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-al
low-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-al
low-methods header, a different error occurs: reason: invalid token ‘xyz' in cors header ‘access-control-al
low-methods’. ...
Allow - HTTP
the al
low header lists the set of methods supported by a resource. this header must be sent if the server responds with a 405 method not al
lowed status code to indicate which request methods can be used. an empty al
low header indicates that the resource al
lows no request methods, which might occur temporarily for a given resource, for example. header type entity header forbidden header name no syntax al
low: <http-methods> directives <http-methods> the comma-separated list of al
lowed http request methods. ...
...icate which request methods can be used. an empty al
low header indicates that the resource al
lows no request methods, which might occur temporarily for a given resource, for example. header type entity header forbidden header name no syntax al
low: <http-methods> directives <http-methods> the comma-separated list of al
lowed http request methods. ...
...st methods, which might occur temporarily for a given resource, for example. header type entity header forbidden header name no syntax al
low: <http-methods> directives <http-methods> the comma-separated list of al
lowed http request methods. ...
405 Method Not Allowed - HTTP
the hypertext transfer protocol (http) 405 method not al
lowed 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 al
low 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 al
lowed 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 al
low 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 al
low header field in a 405 response containing a list of the target resource's currently supported methods. ...
Reflow - MDN Web Docs Glossary: Definitions of Web-related terms
ref
low happens when a browser must process and draw part or all of a webpage again, such as after an update on an interactive site. ...
... ref
low 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.contentsecuritypolicyal
lows 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 al
lowed 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%; overf
low: auto; } p { width: 200%; background: #f5f9fa; border: 2px solid #eaf2f4; padding: 10px; } .scroll-touch { -webkit-overf
low-scrolling: touch; /* lets it scroll lazy */ } .scroll-auto { -webkit-overf
low-scrolling: auto; /* stops scrolling immediately */ } results specifications not part of any standard. apple has a description in the safari css reference. ...
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-al
low-headers’ what went wrong? the response to the cors request that was sent by the server includes an access-control-al
low-headers header which includes at least one invalid header name. the access-control-al
low-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-al
low-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-al
low-headers’ from cors preflight channel what went wrong? the access-control-al
low-headers header is sent by the server to let the client know which headers it supports for cors requests. the value of access-control-al
low-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 al
lowed). this error occurs when attempting to preflight a header that is not expressly al
lowed (that is, it's not included in the list specified by the access-control-al
low-headers header sent by the server). to fix this, the server needs to be updated so that it al
lows the indicated header, or you need to avoid using that header. ...
following-sibling - XPath
the fol
lowing-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
the fol
lowing axis indicates all the nodes that appear after the context node, except any descendant, attribute, and namespace nodes. ...
Index - Web APIs
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. be
low 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 al
lows 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 al
lows 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 al
lows 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 fel
lowship program 2015, archive, fel
lowship 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 al
lows 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 al
low 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 al
low 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 al
low 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 al
lows 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 al
low 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 fol
lowing 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, disal
lowing 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
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 fol
lows 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 f
low. 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, al
low 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
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, al
lowing 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 al
lows 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 al
low 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 fol
lowing 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 fol
lowed 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 fol
lowing 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 al
low 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 fol
lows: 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 fol
lowing: 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 fol
lows 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 fol
low 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 fol
low accepted python paradigms and idoms in the python language and libraries. thus when deciding if the nss/nspr api should be rigidly fol
lowed 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 fol
low 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 al
low 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 fol
lowed by implementing it in the years that fol
lowed. ...
...And 48 more matches
HTML documentation index - HTML: Hypertext Markup Language
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 al
lowing 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, al
lows 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 al
low 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
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 fol
low 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 al
low 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 al
low 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 fol
lowing command, making sure you are inside your project folder: npm install selenium-webdriver note: it is still a good idea to fol
low 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 fol
lowing 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 fol
lows: 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 fol
lows: 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 al
low 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 be
low 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 al
lows 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 fol
lowing 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 fol
lowing: 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
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 al
low 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
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 al
lowevents xul attributes, xul reference no summary! 15 al
lownegativeassertions 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 al
low 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 fol
lows: 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 be
low. 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
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 fol
lowing 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" fol
lowed 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 al
lows 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 al
lowing 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 stackoverf
low'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 al
lows code editors and ides to offer features like code navigation, autocompletion, and smarter hints. safer refactoring: types al
lows 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, al
lowing 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 fol
lows 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 fol
lowing 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 al
low 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 al
low us to take elements contained in a web page and control where they are positioned relative to their default position in normal layout f
low, 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 f
low 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 f
low 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 f
low normal f
low 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 workf
low. 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 al
lows 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 fol
lowing 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 al
lows you to take elements out of the normal document layout f
low, 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 fol
low along with the exercises on your local computer, if possible — grab a copy of 0_basic-f
low.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 fol
low along with the exercises on your local computer, if possible — grab a copy of 0_basic-f
low.html from our github repo (source code here) and use that as a starting point. introducing positioning the whole idea of positioning is to al
low us to override the basic document f
low 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 f
low 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 al
low 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, al
lowing 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 fol
lowing 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 fol
lowing 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
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 fol
lows: 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 al
lowing 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, al
lowing 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 fol
lowed 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 be
low. 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 fol
lowing 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 be
low. the fol
lowing 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 fol
low 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 al
low 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 fol
lowing components: alert.svelte: a general notification box for communicating actions that have occurred. newtodo.svelte: the text input and button that al
low you to enter a new todo item. filterbutton.svelte: the all, active, and completed buttons that al
low 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, al
lowing 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 al
lows interested parties to be notified whenever the store value changes, and an optional set() method that al
lows 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 fol
lowing 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 al
lows, 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 fol
lowing 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 be
low. 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 al
low 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 al
lowing 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 al
lows 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 al
low 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 fol
lowing 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 be
low 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 al
low 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-overf
low-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 be
low. 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?fol
lowing 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 be
low. 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 be
low. 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 ref
low, along with important members of each object that control ref
low 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_ref
low this bit is set when the frame is being actively being ref
lowed. 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_ref
low this bit is set when the frame is being actively being ref
lowed. by default it is set in willref
low(), and unset in didref
low(). many frames' ref
low() method verifies that the bit is set with an assertion. ns_frame_first_ref
low this flag is set on a newly created frame, and later cleared by the frame's ref
low() method when the frame has had its initial ref
low. 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 fol
lowing content will likely see significant revision, though can be used as a reference for security best practices to fol
low 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 overf
lows format string bugs integer overf
lows/underf
lows 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 fol
lowing 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 & → & < → < > → > " → " ' → ' 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 fol
lowing: 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 fol
lowing code: // in the fol
lowing 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 fol
lowing 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 be
low 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 be
low 10 bits per component (10-bit color) al
low 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 be
low 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 fol
lowing 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 al
lowing 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 fol
low along by creating a new index.html file on your computer, filling it with a simple html template, and inserting the be
low 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 fol
lowing: <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 fol
lowing tools and features: jsx, a react-related set of syntax extensions that al
low you to do things like defining component structures inside javascript. you won't need to know react to fol
low 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, fol
lowing 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 fol
low 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 fol
lowing" 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
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
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 be
low. 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 fol
lowing are considered autoplay behavior, and are therefore subject to the browser's autoplay blocking policy: <audio src="/music.mp4" autoplay> and audioelement.play(); the fol
lowing 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 al
low 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 al
low 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 al
low 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 al
lows 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 be
low), 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 al
lows 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 fol
low. if the data entered in a form field fol
lows 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 fol
lowing 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 al
low 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 be
low. 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 be
low. online the jshint homepage provides an online linter, which al
lows 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 al
lowed 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 al
low 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 al
low 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 fol
lowing 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 al
lowed to use the arguments object in the fol
lowing 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 al
lowed to use the arguments object in the fol
lowing 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 al
low 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> <al
lowlist> <directive> the feature policy directive to apply the al
lowlist 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> <al
lowlist> <directive> the feature policy directive to apply the al
lowlist to. see directives be
low 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> <al
lowlist> <directive> the feature policy directive to apply the al
lowlist to. see directives be
low 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, fol
lowed 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 fol
lowing 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 be
low.) 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 fol
lowing 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 be
low): 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 fol
lowing 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 al
lowable 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 fol
lowing 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 al
low 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 be
low 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 al
lows 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 al
lowable 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 be
low 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 fol
lowing 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 be
low 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 be
low 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 fol
lowing 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 fol
lows: 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 fol
lowing 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 be
low 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 be
low 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 f
low 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 fol
lowing 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 fol
lowing just be
low 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 f
lows 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, al
lowing 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 al
lows 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 fol
lowing in pseudocode: if (condition) { code to run if condition is true } else { run some other code instead } here we've got: the keyword if fol
lowed 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 fol
lowing 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 s
low 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 al
lows 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 al
lows 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 al
lows 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? be
low 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 be
low, 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 fol
lowing 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 al
lowed: 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 fol
low 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 al
lows 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 be
low 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 al
lows 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 be
low: 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 fol
lowing 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 be
low 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 fol
lowing 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 fol
lowing 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 fol
lows: #!/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 al
lowed 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 ref
low 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 f
low 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-f
low elements that f
low 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: nsblockref
lowstate nsblockframe nsboxtoblockadaptor the general interaction model is to create a space manager for a block frame in the context of a ref
low, and to associate it with the blockref
lowstate so it is passed down to child frames' ref
low methods. after ref
low, the space manager is destroyed. during ref
low, 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 nsblockref
lowstate). 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 fol
lowing 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, fol
lowed by content, fol
lowed by the closing tag. active learning: creating your first html element edit the line be
low 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 al
lows 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 al
low 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 al
low 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 al
lows 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 al
lows 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, fol
low 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 fol
lowing 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 fol
low 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 al
lows 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 fol
low 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, s
low 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 al
lows 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 fol
lowing 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 fol
lowing 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 be
low 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 fol
lowing 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 (;) fol
lowed 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 al
low 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 be
low 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 be
low. 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. al
low 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: yel
low; 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: yel
low;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 shal
low, 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 fol
lows: /* 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 be
low, 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 fol
lowing 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 be
low 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-f
low: 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 fol
low this format in jsx – on, fol
lowed 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 al
lows you to create markup managed entirely by vue, which can improve developer experience and performance when dealing with complex applications. it also al
lows 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 al
lows 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 be
low 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 be
low. ...
...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 be
low. 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 be
low, you will experience much better results. important background to help you make sense of the instructions that fol
low (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 fol
low 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 be
low. 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
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 fol
lowing 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 fol
lowing 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 fol
lows: 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 al
lows 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 be
low. ...
...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 be
low. to get these sitting side-by-side we have used the fol
lowing 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%; overf
low: 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 fol
lows: 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 al
low 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 al
lows 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 al
lows 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 al
lows 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 fol
low 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 be
low. 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 f
low, and in relation to other boxes on the page: if a box is defined as a block, it will behave in the fol
lowing 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 f
low, 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 f
low, 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. be
low 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 fol
lowing 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 fol
lowing 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 be
low 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 al
low 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 fol
lowing 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 al
low 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 be
low 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 al
lows 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 fol
lowing 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 be
low 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 be
low. 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 fol
lowing 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 f
low 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 fol
low 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 fol
lowing 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 fol
lowing 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 be
low). for t...
...ts a boolean, such as in an if statement (see be
low). 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 fol
lows: for ([initialexpression]; [conditionexpression]; [incrementexpression]) statement when a for loop executes, the fol
lowing occurs: the initializing expression initialexpression, if any, is executed. this expression usually initializes one or more loop counters, but the syntax al
lows 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 be
low, the function contains a for statement that counts the number of selected options in a scrolling list (a <select> element that al
lows 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 al
lows 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 fol
lows: 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 be
low: 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 be
low. 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 be
low. 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 al
lowed 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? fol
lowing standards is certainly not a new organizational phenomenon; organizations require their employees to fol
low 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 al
lows 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 fol
lowing 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 fol
lowing 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 fol
lowing: 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 be
low. 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 be
low 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 be
low 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 fol
lowing situations: web applications intended for
low power devices: applications built with svelte have smaller bundle sizes, which is ideal for devices with s
low 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 shal
low 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 fol
lowing ways: it extends html by al
lowing 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, al
lowing 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 fol
lows a box layout model, rather than being text-f
low 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 al
low 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 be
low. 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 al
low 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 fol
lowing 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 be
low 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 fol
lowing 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 al
lows 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 al
low different pieces of software to be developed and built independently of one another. in order to al
low 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 al
lows 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 be
low 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 be
low cover the ways in which we do so. add-ons add-ons al
low 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 fol
lowing 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 fol
lowing 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 be
low 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 fol
lows: 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 fol
lows: 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" fol
lowed by zero or more "b"s fol
lowed 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 fol
lowing 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 al
low other codecs as well. be
low 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 be
low by fol
lowing 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 fol
lowing 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 fol
lowing to your script, be
low 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 fol
low 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 fol
lowing 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, fol
lowing 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, fol
lowing 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 fol
lowing 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 be
low. 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 fol
lowing: <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, al
lowing 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 fol
lowing: <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 be
low. 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 fol
lowing: <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, al
lowing 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 fol
lowing: <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 al
lowed 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 fol
lowing 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-overf
low 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 al
low 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 al
low 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 al
lowed 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 s
low 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
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 al
lows 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 be
low 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 fol
lows: 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 fol
lowing 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 fol
lowing 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 al
low 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 al
low 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 fol
lowing 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 fol
lowing, 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 al
lows 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 fol
lows: 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 al
lows 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 al
low for predictability and homogeneity in an application; predictability al
lows 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 fol
lowing. 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 s
low 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 fol
low, 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 al
low 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 fol
lowing 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 fol
lowing 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 fol
lowing 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. fol
lowing 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 al
lowing 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 al
lowed 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 fol
lowing 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 fol
lowing 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: al
low 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 'overf
lowable', 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 'overf
lowable' 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 fol
low the above structure closely or adjust the commands be
low 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 fol
lowing 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 fol
lowing 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 be
low. 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 inbe
low, out unsigned long outposition, out nsiwidget outbe
low); 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 al
low us to play/stop the sequencer, and adjust the bpm (beats per minute) to speed up or s
low 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 s
low 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 al
low 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
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 fol
lowing 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 al
lowed author author of the current document or article. link link not al
lowed bookmark permalink for the nearest ancestor section. not al
lowed link not al
lowed canonical preferred url for the current document. ...
...<area> <form> alternate alternate representations of the current document. link link not al
lowed author author of the current document or article. link link not al
lowed bookmark permalink for the nearest ancestor section. not al
lowed link not al
lowed canonical preferred url for the current document. link not al
lowed not al
lowed dns-prefetch tells the browser to preemptively perform dns resolution for the target resource's origin external resource not al
lowed not al
lowed external referenced document is not part of the same site as the current document. not al
lowed annotation annotation help link to context-sensitive help. link link link ...
...And 13 more matches
<input type="email"> - HTML: Hypertext Markup Language
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 fol
lowing 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 al
low 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 al
lowing 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
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 fol
lowing 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 al
low autocorrect while editing this input field. safari only. incremental whether or not to send repeated search events to al
low 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 fol
lowing 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. [al
low] [never for this site] [not now] the term "offline(-enabled) applications" sometimes refers specifically to applications that the user has al
lowed 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 be
low: 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 fol
lowing: 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 al
lows 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 be
low 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 al
lows 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.to
lowercase();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","to
lowercase","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].to
lowercase()},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 al
lows 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 al
lows 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 be
low 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 fol
lowing line be
low 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 fol
lowing line be
low 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 fol
lowing 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, be
low 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 fol
lowing 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 al
lows 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 al
low 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 be
low 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 fol
lowing 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 be
low 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, fol
lowed 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, al
lowing 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 be
low, 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 fol
lowing loop to achieve this: a loop usually has one or more of the fol
lowing 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 fol
lowing: 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 fol
lowing 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 fol
lowing 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 be
low 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 fol
lowing 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 be
low. 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, fol
low 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 fol
low 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 fol
lowing 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" al
low 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 al
lowing 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 s
low 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, al
lowing 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 fol
lowing 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 al
low 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 al
lows 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 fol
lowing 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 f
low key data structures detailed walk-through incrementalism future tech-talks wrap-up, q&a basic data f
low 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 fol
lowing 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() fol
lowed 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 al
low 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 (/) fol
lowed 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 fol
lowing 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 fol
lowing 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. be
low 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 al
lowing 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 fol
lowing 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. al
lowunobservedasmjs 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. al
lowwasmbinarysource 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 fol
lowing 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 fol
lowing 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 al
lowed 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 fol
low 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, al
lowing 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 fol
lowing 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 al
low the server to support signaling and ice negotiation, we need to update the code. we'll have to al
low 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 al
lows 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 (fol
lowing 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 be
low the world space origin. this is shown in the diagram be
low, 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 be
low 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 workf
low 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 be
low. 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 al
low 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 al
low 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 be
low 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 f
low, 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 be
low 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
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 be
low. values static the element is positioned according to the normal f
low 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 f
low 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 f
low, 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 f
low, 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 workf
low 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, al
lowing 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 overf
low has a value other than visible. display: f
low-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
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 al
lows 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 al
lows 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: al
lowing you to describe more precisely what your content is. connectivity: al
lowing you to communicate with the server in new and innovative ways. offline and storage: al
lowing 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
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 f
low 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. al
low 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. al
lowfullscreen 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 al
low="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 fol
lowing 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 be
low. 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 be
low 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 hel
loworld that implements a function called hello. by creating a factory and passing it the contract id for the hel
loworld component and the hel
loworld constructor, we enable xpcom clients to access the hel
loworld component, given its contract id. in this example the hel
loworld 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 fol
lowing 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 al
lows 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>hel
loworld@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 fol
lowing 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 al
lowed 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 al
lowed 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 be
low.) 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 al
low 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 be
low higher-level protocols such as http or imap. it uses tcp/ip on behalf of the higher-level protocols, and in the process al
lows an ssl-enabled server to authenticate itself to an ssl-enabled client, al
lows the client to authenticate itself to the server, and al
lows 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 al
lows 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 al
lows 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 fol
lowing 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 al
low 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 fol
low 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 al
lows 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" al
lows 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 al
low 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 be
low 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! be
low we again have two rules that could apply to the h1. the be
low 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 fol
lowing: 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 al
lows 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 fol
lows: 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 fol
lowing 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 al
low 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 al
lows 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 fol
lowing 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 fol
lowing 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 fol
lowing: 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 fol
lowing 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 al
lows 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 al
low 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 al
lowing 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 al
lowing 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 be
low. 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 be
low: 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 fol
lowing 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 fol
lowing: 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 fol
lowing 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 al
lows 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 al
lows 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 al
lows 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 al
lows 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 disal
lowed 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 fol
lowing 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 be
low 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 al
low 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 fol
lowing: 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 fol
lows 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 al
lowed 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 al
lowed. 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 yel
low, 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 fol
lowing 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 al
lows 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 be
low 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 overf
lowing. 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 f
low 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 overf
low. 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 fol
lowing 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 fol
lowing: 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. al
low <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. al
lowed 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 al
low 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 s
lowing 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 fol
lowing 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
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, al
lowing 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. be
low 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
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 al
low 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 fol
low; 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 be
low 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 fol
lowed 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, al
lowing 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, al
lowing 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
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, al
lowing 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 al
low multiple servers to serve the different requests) authentication (to control access to different resources) logging (al
lowing 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 al
lows 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 al
lowed. the toolkit version format supports the firefox version format but al
lows 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 al
lows 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 al
low 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 s
lowly 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 fol
lowing 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 fol
lows: 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 be
low 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 be
low the minimum size due to the position of the splitter. resizeafter type: one of the values be
low this attribute indicates which element to the right or be
low the splitter should be resized when the splitter is repositioned. closest the element immediately to the right or be
low 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 be
low this attribute indicates which element to the right or be
low the splitter should be resized when the splitter is repositioned. closest the element immediately to the right or be
low the splitter resizes. farthest the element that is the farthest away from the splitter to the right or be
low the splitter resizes. grow the elements to the right or be
low 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 fol
lowing 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 fol
lowing code to your browser.css file somewhere be
low 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 fol
lowing 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 fol
lowing 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 f
low so the boxes display one be
low 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 be
low the other as they do in normal f
low. 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 fol
lowing 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 al
lows 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 al
lows you to run a function repeatedly with a set interval of time between each execution. not as efficient as requestanimationframe(), but al
lows 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 al
lows 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 fol
lowing 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 be
low 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 be
low 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 fol
lowing 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 fol
lowing: <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 fol
lows: 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 fol
lowing 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 al
low 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 al
lows 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 fol
lowing 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 al
low 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 al
low 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. al
low 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 fol
lowing directions carefully before building, and fol
low 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 be
low for a full example). note that in the export example be
low 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 be
low. 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 fol
lowing line to your mozconfig al
lows 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 al
low 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: " fol
lowed 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 fol
low the instructions be
low, 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 be
low 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 fol
lowing. 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 fol
lowing 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 fol
lows: $ 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 hel
loworld component: hel
loworld.idl #include "nsisupports.idl" [scriptable, uuid(xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx)] interface nsihel
loworld : 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 hel
loworld.xpt hel
loworld.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 hel
loworld.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, al
lowing 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 al
lows 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 al
low 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 fol
lowing 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 fol
lows: 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 fol
lows: 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 fol
lows: q: 1 detune: 0 frequency: 350 gain: 0
lowpass: (default) al
lows frequencies be
low 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 be
low 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 be
low 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 be
low 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 al
low 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 workf
low 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 fol
lowing 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 fol
lows 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 be
low: 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 be
low 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 be
low 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, al
lowing 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 al
low 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 be
low screenshot. clicking the down arrow on the right hand side brings up a date picker to al
low you to choose a date; you have to enter the time manually. the edge datetime-local control looks like the be
low; 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 fol
lowing 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
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 be
low 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 ("-"), fol
lowed 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
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 fol
low 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 fol
lowing 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 al
lowed 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 fol
lowing: <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 be
low, single quotes shouldn't be used. you can also specify data schemes (not recommended). data: al
lows 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: al
lows mediastream: uris to be used as a content source. blob: al
lows blob: uris to be used as a content source. f...
...es shouldn't be used. you can also specify data schemes (not recommended). data: al
lows 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: al
lows mediastream: uris to be used as a content source. blob: al
lows blob: uris to be used as a content source. filesystem: al
lows 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 al
low 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 al
lowed 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 fol
lowing: <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 be
low, single quotes shouldn't be used. you can also specify data schemes (not recommended). data: al
lows 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: al
lows mediastream: uris to be used as a content source. blob: al
lows blob: uris to be used as a content source. f...
...es shouldn't be used. you can also specify data schemes (not recommended). data: al
lows 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: al
lows mediastream: uris to be used as a content source. blob: al
lows blob: uris to be used as a content source. filesystem: al
lows 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 al
low 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 be
low. 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 be
low 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 fol
lowing 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 al
lowable 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 fol
lowing 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 al
low 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 fol
lowing 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 al
lows 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 be
low 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 fol
lowing: 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 al
low 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 al
low 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 al
low 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. al
lowevents type: boolean if true, events are passed to children of the element. otherwise, events are passed to the element only. al
lownegativeassertions 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, al
lows 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 fol
lowing 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 fol
lowing lines just be
low 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 be
low 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 al
lows 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 al
low 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 fol
lowing 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 be
low 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 fol
lowing 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 be
low if you want to work on your own computer. save the code be
low 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 be
low to al
low 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 be
low, 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 fol
low the steps be
low. 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 fol
lowing 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 al
lows 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 al
low 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 fol
lowing 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 fol
lowing 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 al
lows 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 f
low 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 be
low 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 be
low 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 overf
lowing it. however, issues arise when you start to view the site on a narrow screen device. the header be
low 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 be
low 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 al
lows 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 s
lowly, 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 al
lows 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 al
low 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 al
low 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 fol
lowing: 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 fol
lowing: create an xpcom component that implements the nsiautocompletesearch interface. make sure the contract id of your xpcom component fol
lows the fol
lowing 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, be
low is an example javascript xpcom component called "simple-autocomplete" that implements the necessary interfaces. note: when copying the examples be
low, 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 al
lows 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 fol
low 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 fol
lowing closely and carefully the steps to create a language pack or a binary file that is ready for installation. repeating the process al
lows 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 fol
lowing 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 fol
low 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 fol
lowing 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 al
low 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 al
lows 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 fol
lowing 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 fol
lowing 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 fol
lows: 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 al
low the use of ascii format for input or output. this formatting fol
lows 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 fol
lowing 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 fol
lowing: 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 be
low.) 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 fol
lowing 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 fol
lowing 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 jslocaleto
lowercase 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_reportallocationoverf
low 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 fol
lowing functions al
low 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 fol
lowing 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 fol
lowing 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 be
low) to point to this new location. when you extract the sdk, it should have the layout seen be
low: 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 be
low 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 fol
lowing 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 al
lowing 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 al
lows 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 al
lows 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 al
lows 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 fol
lowing 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 al
lowauth boolean certain dochshells (like the message pane) should not throw up auth dialogs because it can act as a password trojan. al
lowdnsprefetch boolean attribute that determines whether dns prefetch is al
lowed 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 copytofol
lowinglinks(in nsifile newparentdir, in astring newname); void copytofol
lowinglinksnative(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. fol
lowlinks 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 fol
lowlinks 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 al
low 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
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 fol
lowing 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 fol
lowing 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
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 al
low 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 al
lowmouserotation = true; const al
lowkeyboardmotion = 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. al
lowmouserotation if true, you can use the mouse to pitch and yaw the view angle. al
lowkeyboardmotion 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 fol
lowing 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 fol
lowing 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 al
lows 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 be
low. 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 be
low. 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 fol
lowing 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 fol
lowing 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 al
lows 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-f
low/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 fol
low 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 al
lowed 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 fol
lowing 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 fol
lowing 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 be
low. 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 yel
low #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 cornf
lowerblue #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 al
lows us to specify subtitles for a video using the <track> element. the various attributes of this element al
low 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 fol
low 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="al
lowfullscreen" value="true" /> <param name="wmode" value="transparent" /> <param name="flashvars" value="controlbar=over&image=img/poster.jpg&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&image=img/poster.jpg&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 be
low" /> </object> <!-- offer download --> <a href="video/tears-of-steel-battle-clip-medium.mp4">download mp4</a> </video> <figcaption>© 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>© 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 al
lows 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 be
low: #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 fol
lowing 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 fol
lowing 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 fol
lowing 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. fol
lowing 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 be
low is free-standing (it is safe to assume there is no other javascript on the webpage other than the be
low 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 be
low 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 be
low. 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 fol
lowing 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 s
lower 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 be
low 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 be
low 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 fol
lowing 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 al
lowing 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 al
lowing 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) al
lows 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, al
lows 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 al
low 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 al
low 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 al
lowing 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 be
low 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 be
low 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. fol
lowing 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 fol
lows: <button class="plain" label="push me" /> then the fol
lowing 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 fol
lowing 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 fol
lowing 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 al
lowed 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 al
low 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
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 be
low. 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 al
low 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 al
lowed 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 be
low 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 al
low 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 be
low. <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 be
low 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 be
low shows a detection heuristic in action. example 1: verifying the flash plugin version be
low, 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 al
low 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 fol
lowing be
low 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 fol
lowing 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 fol
lowing 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 be
low 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 f
low direction. sentences run horizontally. vertical-rl: right-to-left block f
low direction. sentences run vertically. vertical-lr: left-to-right block f
low 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 f
lows 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 fol
lowing 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 overf
low the box. you need to make a decision about what happens with the overf
low. ...
...he file by default. sizing images as you already know from fol
lowing 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 overf
low the box. you need to make a decision about what happens with the overf
low. in the example be
low 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 overf
lows the box. so what can we do about the overf
lowing 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 al
lows 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 be
low) 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 be
low), 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 overf
low 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 be
low 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 fol
lowing 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 al
low 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 fol
lowing 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 be
low 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 fol
lowed 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 fol
lowing 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 fol
low 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 fol
lowing inside the <script> element: function displaymessage() { } we start off with the keyword function, which means we are defining a function. this is fol
lowed 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 al
low 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 al
lows 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 fol
low, al
lowing 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 be
low. <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 fol
low 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 fol
low 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 be
low). in some cases, option arguments must be enclosed in quotation marks (this is noted in the option descriptions be
low). 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 be
low – giving further access to cache entries – see nsicacheentry more be
low – 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 be
low) 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 fol
lowing 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 be
low. 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 al
lowed 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 al
lows 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 al
lows 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 fol
lowing 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 fol
lowing 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 al
lows 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 al
lows 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 fol
low 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 al
low 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 s
lowing 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 s
lowing 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 al
low 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 al
low 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 al
low 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 al
lows 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 al
low 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 al
lows 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 fol
lowing environment variables: nss_ssl_enable_renegotiation values: [0|n|n]: ssl_renegotiate_never never al
low 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 fol
lowing 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 be
low the code. the code differs for each spidermonkey version, please choose right version for your spidermonkey. spidermonkey 24 // fol
lowing 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 fol
lows. 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 be
low. 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 be
low 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 be
low. 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 al
low 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 f
low in a timeframe. history views must be organized and as concise as possible. each visit is associated with a favicon, to al
low 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 fol
lowing 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, be
low). 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 al
lows, 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 fol
lowing 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 fol
lowing 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 fol
lowing codelet: [nsspeechsynthesizer alloc] it passes an alloc message to the nsspeechsynthesizer class, in objective-c syntax. it performs the fol
lowing 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 notal
lowederror 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 fol
lowing 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 al
lowing 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 f
lows 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 be
low). the chunks inside the stream are read by a reader — this processes the data one chunk at a time, al
lowing 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 al
lows 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 fol
lowing 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 fol
lowing 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 al
low 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: al
lowing 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 al
lows 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 fol
lowing 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 al
low 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 fol
low 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, al
lowable keywords will be listed in the fol
lowing form. the fol
lowing values are the pre-defined keyword values al
lowed 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 fol
lowing. .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 al
low 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 al
low 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 fol
lowing 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: yel
low; } .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
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 be
low. 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 al
lowed (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 fol
lowing 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
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 al
low 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 al
lowed values are nodownload, nofullscreen and noremoteplayback. use t...
...tribute is specified). the al
lowed 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 al
lowed 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-al
low-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
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 al
lowlisted domains, ignoring all other script (including inline scripts and event-handling html attributes). as an ultimate form of protection, sites that want to never al
low scripts to be executed can opt to globally disal
low 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 al
lowed 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 al
lowed to load for that page. for example, a page that uploads and displays images could al
low 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 al
lowed. 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 al
lows 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 al
lowed. 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 al
lows 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 al
lowed 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 fol
lowing: <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) fol
lowed 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 fol
lowed by a
lowercase or uppercase latin letter "b" (0b or 0b). if the digits after the 0b are not 0 or 1, the fol
lowing 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 fol
lowed by a
lowercase or uppercase latin letter "x" (0x or 0x). if the digits after 0x are outside the range (0123456789abcdef), the fol
lowing 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 fol
lows: 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 fol
lowing 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 fol
low 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 fol
lowing 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 al
lows 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 fol
low 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 fol
lowing 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 fol
lowing arguments call(boundthis, ...args). where boundthis is [[boundthis]], args is [[boundarguments]], fol
lowed 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]], fol
lowed 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 s
lower 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 be
low 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 be
low. 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 be
low. 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 be
low. 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 fol
lowing 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 fol
lows 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 fol
lows: 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 f
lows. 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 s
low 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 fol
low. 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 fol
lowing: 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 al
lows 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 al
low 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. be
low 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 be
low 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 fol
lowing 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 fol
lowing 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 al
lows 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 be
low. 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 fol
lowing 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 be
low 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 al
lowed 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 al
lows 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 fol
lowing method to find it. from seamonkey's menu bar, choose tools – web development – javascript console. copy the fol
lowing 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 fol
lows: <content uri="?var"/> the question mark indicates that the text fol
lowing 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 fol
lowing 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 al
low 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 be
low: 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 fol
lowed 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 fol
lowing 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 al
low 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. al
lowevents 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 al
lowing us to build 3d vr landscapes using a system familiar to web developers, which fol
lows 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 fol
low 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 fol
lowing 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 fol
lowing 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 be
low 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 s
low 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 overf
low, a set height can cause content to overf
low if there is more content than the element has space to fit inside it. due to this problem of overf
low, 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 fol
lows. 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 be
low, 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 be
low 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 al
low 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 be
low 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 be
low 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 fol
lowing 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 al
lowing 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 fol
lowing 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 s
lowly, 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. workf
lows 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 fol
lowing 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 fol
lows. 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 al
lows 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-al
low entitlement disal
lowed. rather than disabling sip (which has security implications), it is recommended to debug with try builds or local builds. the differences are explained be
low. 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 be
low). at this time, developers can obtain a hardened runtime build with the com.apple.security.get-task-al
low entitlement al
lowed 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, fol
low 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 fol
lowing 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 fol
lowing 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 & and not simply &. <tree type="places" place="place:terms=mozilla&onlybookmarked=1&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 al
lows 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 al
low 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 fol
lowing 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 fol
lowing 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 be
low) and are connected, there are some basic rules you should fol
low 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 al
low you to connect to irc networks. you will need to use the fol
lowing information to configure the server connection: server: irc.mozilla.org port: 6667 (default) or 6697 (ssl) desktop clients desktop clients tens to al
low 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 al
low 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 fol
lowing 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 fol
lowing diagram (from the intel power governor documentation) shows how machines using recent intel processors are constructed. the important points are as fol
lows. 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. fol
low 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 al
lows 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 be
low 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 fol
lowing 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 be
low. ...
... 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 be
low. 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 be
low). 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_al
low_weak_signature_alg boolean (any non-empty value to enable) enables the use of md2 and md4 inside signatures. this was al
lowed 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 al
lowed 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 fol
low 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 al
lows 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 al
lows 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 be
low. 1. generate the key using the fol
lowing 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 al
lows 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, al
lowing 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 al
lows 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 markpageasfol
lowedbookmark(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 al
low 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 al
lows source level debuggers to more easily "fol
low" 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 be
low. ...
...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 be
low. ...
...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 fol
lowing 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 al
lows 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 fol
low 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 fol
lowing 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 be
low 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 s
lows 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 fol
lowing: 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 fol
lowing 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 al
lows 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 fol
low 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 fol
lowing 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 al
lows 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 be
low throw. convention for descriptions of properties and methods be
low, 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 fol
lows: it al
lows 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 be
low. 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 f
low, 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 al
low 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 fol
lowing 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, al
lowing 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 s
low 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. be
low 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 be
low. 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 fol
low 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 al
low 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 fol
lows 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 al
low 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 al
low 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 al
low 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 al
lows 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 fol
lowing (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 al
lows 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; overf
low: 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 f
low fol
lowing 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 fol
lowing 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 overf
low has a value other than visible elements with display: f
low-root or display: f
low-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 f
low-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 be
low 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 be
low 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 fol
low 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 fol
lowed 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 be
low. 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 be
low 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 fol
lowing 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 al
lows 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 fol
lowing 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 fol
lowing 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, cornf
lowerblue, 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
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 al
low 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 al
lowed 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 al
lowed 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-al
low-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
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 fol
lowing attributes: attribute description accept one or more unique file type specifiers describing file types to al
low 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 al
lows the user to select more than one file. non-standard attributes in addition to the attributes listed above, the fol
lowing 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
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 fol
low 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 fol
lowing 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
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 fol
lowing 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 fol
lowing: 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 be
low shows the source for a set of elements marked up with itemprop attributes, fol
lowed 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 al
lowed 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 al
low 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 al
low 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 al
lowed 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 al
lows 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 al
lows 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 al
lows 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 be
low 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 be
low: 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 al
low 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 (be
low). 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 fol
lowing 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 fol
lowing 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 be
low. 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 be
low 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 fol
lowing sections provide a brief overview of each of the image file types supported by web browsers. in the tables be
low, 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 fol
lowing 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 be
low. ...
...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 be
low. tcp s
low start / 14kb rule the first response packet will be 14kb. this is part of tcp s
low start, an algorithm which balances the speed of a network connection. s
low start gradually increases the amount of data transmitted until the network's maximum bandwidth can be determined. in tcp s
low 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 s
low 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 s
low 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 s
low 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 al
low 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 fol
low 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) al
lows 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 s
lower 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 fol
lows 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 f
lower.</text> <g id="f
lower"> <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 al
lowing 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 al
lows 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 al
lowed prefixes are sha256, sha384, and sha512), fol
lowed 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 be
low. ...
...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 be
low. 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 be
low 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 fol
lowing 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 fol
lowing 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 al
lows firefox to treat your interface as a first-class citizen. for example, in the future firefox may al
low 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. al
low 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 s
low 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 fol
lowing 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 fol
lowing 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 fol
lows 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 fol
lowing 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 al
lowed to access example.com, "file:///c:/foo.xhtml" will be al
lowed 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〉 be
low. ...
... using the placeholder 〈namespace〉 be
low. 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 fol
low 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 fol
low 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 al
lows 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 yel
low 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 be
low. 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 fol
lowing 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 * ref
low. */ 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 * ref
low. */ 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 fol
lowing 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, al
lowing 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 fol
lowing 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 be
low 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 fol
lowing 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, fol
lowed 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 be
low, 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 al
lowed 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 be
low: <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 fol
lowing 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 al
low 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 fol
lowing 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 fol
lowing 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 f
low 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 al
lows 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 al
low 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 al
lows 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 al
lows 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 fol
lowing 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 fol
lowing 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 al
lows 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 al
lows 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
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, al
lows legacy webpages to be rendered as their authors intended, fol
lowing 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 fol
low 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 al
lows 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 al
low 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 al
low 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 fol
lowing 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 fol
lowing 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 al
lows 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 fol
lowing 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 fol
lowing 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 al
lows 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, al
lowing 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 be
low. 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 fol
lowed 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, fol
lowed by an equals sign (=), fol
lowed 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 be
low. 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 al
low 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 fol
lowing 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 al
lows 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. ...
...rf
low: 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 */ overf
low: 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 al
lows 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 al
lowed 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 fol
lowing 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 fol
lows 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 al
lows 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 fol
low 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 fol
lowing 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 be
low 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 fol
lowing: # 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 fol
lowing: # 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 be
low). creating the protocol pecho.ipdl let's start by saving the fol
lowing file to ./dom/ipc/pecho.ipdl. we will explain what all the parts mean be
low. 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 fol
lowing 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 al
low 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 fol
lows - 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 fol
lowing 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 be
low 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 be
low). 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 fol
low 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 al
low 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 fol
lowing 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 al
low slight modifications (e.g. rtl or wider display) gives the possibility to customize content per locale simple workf
low, 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 fol
lowing 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 be
low. ...
...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 fol
lowing 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 fol
lowing 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 fol
lowing: 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 al
lows 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 fol
lowing 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 al
low the use of ascii format for input or output. this formatting fol
lows 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 fol
lowing 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 al
low the use of ascii format for input and output. this formatting fol
lows 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 fol
low 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 al
lows 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 fol
lowing 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 fol
lows: 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 al
low the use of ascii format for input and output. this formatting fol
lows rfc #1113. -c crl-gen-file specify script file that will be used to control crl generation/modification. see crl-cript-file format be
low. 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
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 be
low. 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 workf
low. 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 be
low 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 be
low. 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 fol
lowing 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 al
low 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 al
lows 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" al
lows these paths to be reconstructed more easily. when the user starts browsing (for example, by typing in a link or fol
lowing 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" al
lows these paths to be reconstructed more easily. when the user starts browsing (for example, by typing in a link or fol
lowing 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 fol
lowing a bunch of links or redirects. a session is ended when a new url is typed in or selected from bookmarks. these session ids al
low 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 fol
lowing 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. be
low, 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 al
lows 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 al
lows 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 al
lowpipelining boolean this attribute is a hint to the channel to indicate whether or not the underlying http transaction should be al
lowed 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 sanitizeral
lowcomments (1 << 0) flag for sanitizer: al
low 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 sanitizeral
lowcomments (1 << 0) flag for sanitizer: al
low comment nodes. sanitizeral
lowstyle (1 << 1) flag for sanitizer: al
low <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 al
low 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 be
low with the @myself.com/my-component;1 contract. // constructor function hel
loworld() { }; hel
loworld.prototype = { hello: function() { return "hello world!"; }, queryinterface: function(aiid) { if (!aiid.equals(components.interfaces.nsisupports) && !aiid.equals(components.interfaces.nsihel
loworld)) 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 fol
lowing: // 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 al
low 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 al
lowing 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 al
low 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(). be
low 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. be
low 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 be
low. 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 be
low. to try this for yourself, you can use the code snippet be
low. 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 be
low 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 fol
lowing, 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 be
low. this fol
lowing 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 fol
lowing 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 fol
lowing: 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 al
lowed on this object store. read_write 0 modification operations are al
lowed 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 fol
lowing 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 al
lowed. 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 fol
lowing 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 fol
lows 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 fol
lowing 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 fol
lowing 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 overf
low 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 al
lows 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 be
low. 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 al
lows 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 fol
lowing 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 al
lows 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 fol
lowing sub-sections contain short descriptions of each interface and property. pointerevent interface the pointerevent interface extends the mouseevent interface and has the fol
lowing properties. (all of the fol
lowing 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_al
lowed_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_al
lowed_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_al
lowed_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 be
low. 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, be
low, 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 al
lowing 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 be
low 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 al
low 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 fol
lowing 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 fol
lowing 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 be
low 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 f
low 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 be
low. 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 al
lowed 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 fol
lowing 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 al
low 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 al
low 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 al
low 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 be
low. 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 be
low. 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 fol
lowing 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; overf
low: 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 overf
low 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-f
low 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 al
lowed 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 al
lowed 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 fol
lowing 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 be
low 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 fol
lowed 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 be
low. 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-f
low -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-f
low -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, fol
lowed 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 fol
lows 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 be
low. 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 be
low. 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 be
low. 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 be
low. <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 be
low. 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 fol
lowing 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
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-f
low && dense? ] <'grid-auto-columns'>? values */ grid: 200px / auto-f
low; grid: 30% / auto-f
low dense; grid: repeat(3, [line1 line2 line3] 200px) / auto-f
low 300px; grid: [line1] minmax(20em, max-content) / auto-f
low dense 40%; /* [ auto-f
low && dense? ] <'grid-auto-rows'>? / <'grid-template-columns'> values */ grid: auto-f
low / 200px; grid: auto-f
low dense / 30%; grid: auto-f
low 300px / repeat(3...
...And 6 more matches
resize - CSS: Cascading Style Sheets
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 be
low. ...
... /* 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 be
low. values none the element offers no user-controllable method for resizing it. both the element displays a mechanism for al
lowing 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 be
low. values none the element offers no user-controllable method for resizing it. both the element displays a mechanism for al
lowing the user to resize it, which may be resized both horizontally and vertically. horizontal the element displays a mechanism for al
lowing the user to resize it in the horizontal direction. vertical the element displays a mechanism for al
lowing the user to resize it in the vertical direction. block the element displays a mechanism for al
lowing 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
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 fol
lowing 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
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 be
low 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 fol
lowing 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 al
low 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
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 be
low. 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 al
lowed (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 be
low: <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
the source for this interactive example is stored in a github repository. if 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
<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 al
low 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 f
low 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 fol
lowing example which demonstrates an inline element: <div>the fol
lowing 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
cross-origin resource sharing (cors) is a standard that al
lows a server to relax the same-origin policy. this is used to explicitly al
low 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 disal
lows 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 fol
lowing: cross-origin request blocked: the same origin policy disal
lows 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 al
lows 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 al
lows 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. al
low 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 al
lows 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 al
lowed 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 al
lowed 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 al
lows 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 fol
lowing: <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 be
low, single quotes shouldn't be used. you can also specify data schemes (not recommended). data: al
lows 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: al
lows mediastream: uris to be used as a content source. blob: al
lows blob: uris to be used as a content source. f...
...es shouldn't be used. you can also specify data schemes (not recommended). data: al
lows 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: al
lows mediastream: uris to be used as a content source. blob: al
lows blob: uris to be used as a content source. filesystem: al
lows 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 al
low 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 al
lowed 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 fol
lowing: <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 be
low, single quotes shouldn't be used. you can also specify data schemes (not recommended). data: al
lows 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: al
lows mediastream: uris to be used as a content source. blob: al
lows blob: uris to be used as a content source. f...
...es shouldn't be used. you can also specify data schemes (not recommended). data: al
lows 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: al
lows mediastream: uris to be used as a content source. blob: al
lows blob: uris to be used as a content source. filesystem: al
lows 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 al
low 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 al
lowed 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 al
lows 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 al
lows 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 fol
lowing: <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 be
low, single quotes shouldn't be used. you can also specify data schemes (not recommended). data: al
lows 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: al
lows mediastream: uris to be used as a content source. blob: al
lows 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 al
lowed 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 fol
lowing: <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 be
low, single quotes shouldn't be used. you can also specify data schemes (not recommended). data: al
lows 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: al
lows mediastream: uris to be used as a content source. blob: al
lows blob: uris to be used as a content source. f...
...es shouldn't be used. you can also specify data schemes (not recommended). data: al
lows 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: al
lows mediastream: uris to be used as a content source. blob: al
lows blob: uris to be used as a content source. filesystem: al
lows 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 al
low 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 fol
lowing values: al
low-downloads-without-user-activation al
lows 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 be
low, single quotes shouldn't be used. you can also specify data schemes (not recommended). data: al
lows 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: al
lows mediastream: uris to be used as a content source. blob: al
lows 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 be
low, single quotes shouldn't be used. you can also specify data schemes (not recommended). data: al
lows 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: al
lows mediastream: uris to be used as a content source. blob: al
lows 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
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 al
low other hashing algorithms than sha-256 in the future. see be
low 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 al
lows 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 be
low 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 be
low 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 al
lowed. 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 fol
lowing 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 fol
lowing: if the input string begins with "0x" or "0x" (a zero, fol
lowed 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 fol
lowing 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 fol
lowing 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 be
low. 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 s
low 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 be
low 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 be
low 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 overf
low:hidden in ua style sheet implementation status unknown al
low overf
low: auto; to clip and show scroll bars implementation status unknown al
low overf
low: 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) al
low 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 fol
lowing: 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 al
low 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 al
low 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 fol
lowing 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 al
lows 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 fol
lowing 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 fol
lowing 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 fol
lowing: 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 be
low. 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 al
lows 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.hel
loworld.label;" tooltiptext="&xulschoolhello.hel
loworld.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 al
lows 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 fol
lowing 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 fol
lowing 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 hel
loworld2 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 (hel
loworld2.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 fol
lowing 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 fol
lowing 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 fol
lowing 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 fol
lowed 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 fol
lowing 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 fol
lowing 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 fol
lowing diagram represents an overview of the process and the pieces involved: you will need the fol
lowing 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 be
low. 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 be
low. ...
...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 fol
lows: <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 fol
lowing 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 be
low). 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 fol
lows 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 fol
lowing 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 fol
lowing 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 al
low 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 be
low menubar across width of window containing main toolbar (and its contents) application-specific content area be
low 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 be
low. 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 be
low. 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 al
lowed. 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 be
low. 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 be
low. ...
...And 5 more matches
Localization - Archive of obsolete content
xul and xml provide entities which are a convenient way of al
lowing 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 < and > are examples of entities which can be used to place less than and greater than signs into the text. xml has a syntax which al
lows 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 fol
lowing 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 be
low 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 al
low 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 be
low: 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 fol
lows: 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 fol
lowing: 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 al
lows 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 al
lows 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 fol
lowing 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='overf
low: auto;'. this may also be used with any other container element. examples the fol
lowing 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 al
low 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 overf
low: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 al
lows 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 be
low the title bar. this al
lows 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 al
low 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 al
lows 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 be
low), 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 fol
lowing 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 fol
lowing: 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 s
lower 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 al
lows 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 fol
lowing foreach (which can work with arrays, objects, or e4x objects) are quite convenient in iterating over complex structures such as e4x would not normally al
low. /* 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 fol
lowing 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 " 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 be
low). 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 be
low) 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 fol
lowing 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 al
low 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 al
lowed 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 al
lows you to change volume (see be
low). 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 s
low-down. there are signals at the beginning and end of animations that al
low 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 fol
lowing 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 be
low 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 fol
low 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. fol
low 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 al
lows 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 fol
low 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 — be
low 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 fol
lowed 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 fol
lowing 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 fol
lowing 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 al
low 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 fol
lowing 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 fol
lowing 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 f
low 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 al
low 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 fol
lowing (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 be
low 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 be
low. 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 fol
lowing: 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 fol
lowing line be
low 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 be
low 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 fol
lowing 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 fol
lowing: 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 fol
lowing 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, fol
lowed 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 al
low 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, al
lowing 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 al
low 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 al
low 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 fol
lowing 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 fol
lowing to your prefs.js: user_pref("accessibility.browsewithcaret", true); accessibility prefs reference the fol
lowing 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 fol
low 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 al
lows 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 fol
lowed 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 al
lows 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 fol
lowing: 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 fol
lows 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 fol
lowing 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 fol
lowing 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 al
low 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
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 al
lows 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 al
lowing 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 be
low. 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 al
lowed 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 fol
lowing 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 al
lowed 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 al
lows 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 s
lower. 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 be
low. 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 be
low. 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 al
lows 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, be
low 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 fol
low the instructions be
low 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 al
lows 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 fol
lowing asn.1 structure: certificatesequence ::= sequence of certificate see the section be
low 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 fol
lowing asn.1 structure: certificatesequence ::= sequence of certificate see the section be
low 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 fol
lowing line: -----begin certificate----- fol
lowing 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_al
low_network_fetching cert_rev_m_forbid_network_fetching cert_rev_m_al
low_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 fol
low 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 al
low 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 be
low 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. be
low, 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 be
low 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 be
low, 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 al
low the use of ascii format for input or output. this formatting fol
lows 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 al
lowed. -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 al
low 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 al
lows 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 fol
lows. 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 al
low method chain. methods of js::readonlycompileoptions method description bool mutederrors() const determines if errors are muted. the web platform al
lows scripts to be loaded from arbitrary cross-origin sources. this al
lows 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 fol
lowing 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 be
low. 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 fol
lowing 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 al
lowed, 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 s
low 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 be
low. 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 fol
lowing 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 be
low. 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
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 al
low 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 be
low. 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 be
low. 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 be
low). 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 be
low. 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 al
lows 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 is
lowmemory(); 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. is
lowmemory 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 is
lowmemory(); 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 s
low. 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 s
low. 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 be
low 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
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 fol
lowing 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 be
low. 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 al
low 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 be
low. 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 fol
lowing 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. allocationslogoverf
lowed 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 al
lows 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 fol
lowing 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 fol
lowing 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 al
lows 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 fol
lowing 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 be
low 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 fol
lowing 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 fol
lowing 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.s
low 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 s
low 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 al
low 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 fol
lowed 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 fol
lowing 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 be
low "fonts used" with additional controls for editing the fonts’ characteristics. for standard (static) fonts, you will be able to change the settings listed be
low 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 be
low) 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
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 fol
lowing 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 al
lows 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 al
low 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, al
lows 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 fol
lowing 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 fol
lowing 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 be
low 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 fol
lowing 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 fol
lowing sections. methods the fullscreen api adds methods to the document and element interfaces to al
low 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 al
lowed, 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 fol
lowed 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 fol
lowed 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. al
lowdirs boolean: part of the non-standard directory upload api; indicates whether or not to al
low 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 fol
lowing 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 fol
lows 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 fol
lowing 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 al
lowed 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.bufferedamount
lowthreshold the rtcdatachannel property bufferedamount
lowthreshold 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, al
lowing 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 be
low 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 be
low 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 al
lowing 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 al
low 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 fol
lowing: 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 fol
lowing 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 al
low 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 be
low. 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 be
low 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 be
low, 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 be
low, the container of a radiogroup is ass...
...And 5 more matches
@supports - CSS: Cascading Style Sheets
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 fol
lowed by a value, separated by a colon). the declaration must be surrounded by parentheses. the fol
lowing 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 f
low 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 be
low 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 al
low 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 fol
lowing 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 be
low 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
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 be
low. 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-f
lowflex-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-f
lowgrid-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 al
low 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 fol
lowing 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 fol
lowing declarations ... font-style: italic; font-weight: bold; font-size: .8em; line-height: 1.2; font-family: arial, sans-serif; ... can be shortened to the fol
lowing: 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; overf
low: hidden; transition: all 0.3s; -moz-box-sizing: border-box; -webkit-box-sizing: border-box; box-sizing: border-box; } .ui-dropdown-list:hover { overf
low: 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 fol
lowing: 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, \, fol
lowed 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 (-) fol
lowed 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 be
low). 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 be
low). 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 al
low 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 al
lows 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 al
low 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
<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 al
lows 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 al
low you to turn single values on and off. where multiple controls exist, radio buttons al
low one to be selected out of them all, whereas checkboxes al
low 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 fol
lowing 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
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 al
low 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 al
lowed 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 fol
lowing: <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 be
low, single quotes shouldn't be used. you can also specify data schemes (not recommended). data: al
lows 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: al
lows mediastream: uris to be used as a content source. blob: al
lows blob: uris to be used as a content source. f...
...es shouldn't be used. you can also specify data schemes (not recommended). data: al
lows 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: al
lows mediastream: uris to be used as a content source. blob: al
lows blob: uris to be used as a content source. filesystem: al
lows 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 al
low 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 be
low, single quotes shouldn't be used. you can also specify data schemes (not recommended). data: al
lows 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: al
lows mediastream: uris to be used as a content source. blob: al
lows 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 be
low, single quotes shouldn't be used. you can also specify data schemes (not recommended). data: al
lows 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: al
lows mediastream: uris to be used as a content source. blob: al
lows 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 fol
lowing \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 fol
lowing 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 fol
lowing 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 al
lowed. ...
...railing commas are not al
lowed. 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 fol
lowing 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 be
low. when the code new foo(...) is executed, the fol
lowing 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 fol
lowing 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
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 be
low 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 fol
lowing 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 al
lows 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 fol
lowing 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 al
lows 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
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 al
low 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 fol
lowing 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 be
low. 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 fol
lowing 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 be
low. 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 fol
lowing 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 be
low shows how you should save a path in user prefs. storing nsifile in preferences the fol
lowing 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. fol
low 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 be
low). 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 be
low. 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 be
low: /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 be
low. ... <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 s
low 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 fol
lowing 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 al
lows 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 be
low. ...
...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 fol
lowing 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 fol
lowing 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, al
lowing 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 al
lows 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 al
low 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 fol
low. 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 fol
lowing 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 be
low 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 fol
lowing 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 al
lows 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: yel
low;} ...coupled with this html: <p class="warning">warning!</p> in netscape 6, the paragraph in question will have neither red text nor a yel
low 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 be
low 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 b
lowing 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 fol
lowing 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 al
lows 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 al
lowed 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 al
lows an implementor to hide both the class declaration and creation details of an object, an extremely important step for al
lowing 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 fol
lowing 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 al
lows 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, fol
lowed 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 overf
low this event is only sent to a box or other layout element with a css overf
low 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 overf
low event will be fired. depending on the value of the overf
low 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 fol
lowing name. copy the name from here and paste it, to avoid typing errors: custom-toolbar-button@example.com perform the fol
lowing 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 fol
lowing 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 fol
lowing 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 be
low 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 fol
lowing: 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 be
low. 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 be
low. <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 fol
lows: <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 be
low will be expanded as fol
lows, 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, fol
lowed 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 fol
lowing 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.al
low_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 fol
lowing 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 fol
lowing 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 fol
lowing 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 al
lows 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 fol
lows 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 fol
lows: <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 be
low are equivalent: <vbox></vbox> <box orient="vertical"></box> the fol
lowing 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
« 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 al
lows 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 al
lows 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 al
lows 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 al
lows 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 al
low 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 fol
lowing 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 be
low. 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 be
low. 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 be
low 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 fol
lowing css rule when you want to use the value none: menupopup > menuitem, menupopup > menu { max-width: none; } dir type: one of the values be
low 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 al
lowed 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, al
lowthirdpartyfixup ) addtab( url, {referreruri: ..., charset: ..., postdata: ..., owner: ..., al
lowthirdpartyfixup: ..., 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, al
lowthirdpartyfixup ) loadonetab( url, { referreruri: ..., charset: ..., postdata: ..., inbackground: ..., al
lowthirdpartyfixup: ..., 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 al
lows 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 be
low 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 fol
lowing css rule when you want to use the value none: menupopup > menuitem, menupopup > menu { max-width: none; } dir type: one of the values be
low 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 al
lowed 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 fol
low 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 fol
lowing 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) fol
low 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 al
lows 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
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-f
low-fromthe -ms-f
low-from css property is a microsoft extension that gets or sets a value identifying a region container in the document that accepts the content f
low from the data source.-ms-f
low-intothe -ms-f
low-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 be
low 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 be
low, 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” – al
lows 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 fol
low 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 al
lowing your users to directly play your games online — at least in demo form. also, you should do some work on seo to al
low 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 — fol
low 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 fol
lowing line in the same place as the other event listeners, just be
low 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 fol
lowing 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 fol
lowing 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 fol
lowing just be
low your drawball() function: function drawpaddle() { ctx.beginpath(); ctx.rect(paddlex, canvas.height-paddleheight, paddlewidth, paddleheight); ctx.fillstyle = "#0095dd"; ctx.fill(); ctx.closepath(); } al
lowing 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 fol
lowing 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 be
low it put the call to animations.add() seen be
low: 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 fol
lowing 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 be
low, 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 fol
lowing 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 fol
lowing 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 be
low 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 fol
lowing changes to the look of the content in this example: give the element with an id of special a yel
low 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 be
low 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 fol
lowing 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 be
low. 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 fol
lowing our project, pause here to read dealing with files and html basics.) open your index.html file. paste the fol
lowing 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 fol
lowing lines (shown be
low), 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 (be
low) 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 be
low. 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 fol
lowing 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 fol
lowing 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 fol
lowing: 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, al
lowing 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 be
low. 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 al
low 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 be
low, 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 be
low, 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 be
low 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 s
lowly 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 fol
lowing 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 fol
lowing 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 fol
lows: 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 be
low. 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 s
low 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 fol
low. 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 al
lows 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 fol
lowing 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 fol
lows. 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 al
low 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 al
lows 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 al
lows 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 al
lows 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 be
low 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 al
lows 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 al
lows users to select arbitrary content with the keyboard and move through content as if inside a read-only editor. this al
lows 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 al
lowing 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, al
lowing keyboard access to document structure. the find bar al
lows for quick navigation to links and text searching without opening a separate dialog -- this al
lows 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 fol
lowing 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 al
lows for quick navigation to links and text searching without opening a separate dialog -- this al
lows 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 fol
lows: { "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, fol
lowing 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 al
low 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 fol
lowing navigation methods al
low navigation through the browsing history of the <iframe>. they are necessary to be able to implement back, forward, stop, and reload buttons. htmliframeelement.reload() al
lows reloading of the <iframe> element content. htmliframeelement.stop() al
lows 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 fol
lowing methods al
low 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 fol
lows: 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 fol
lows: 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 fol
lowing 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, fol
low 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, ⟵ ⟵ ⟶ 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 be
low 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 s
low as to be useless. the build is going to be very s
low, 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. be
low 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 be
low 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 al
low 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 fol
lowing 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 fol
lowing 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 fol
lowing 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, be
low, 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 be
low). makes nsrandfile usable with /dev/urandom. nss_al
low_weak_signature_alg boolean (any non-empty value to enable) enables the use of md2 and md4 hash algorithms inside signatures. this was al
lowed by default before nss 3.12.3. nss_hash_alg_support string specifies algorithms al
lowed 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 al
low 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 / "highfrequency
lowlimit" controls for dynamic heap growth. when the gc is in "high frequency" mode (see above) then, the heap will be al
lowed 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 fol
lowing 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 al
low 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 fol
lowing 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 fol
lows 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 be
low. in the fol
lowing 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 fol
lowed 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 be
low. 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 fol
lowing 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. al
lowcallbacks: deprecated/redundant from firefox 34. this option al
lows 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 al
low 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 al
lowadjacent, 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 al
lowadjacent, 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 al
lowadjacent, in rangearray results); native code only! void getrangesforintervalcomarray(in nsidomnode beginnode, in print32 beginoffset, in nsidomnode endnode, in print32 endoffset, in prbool al
lowadjacent, 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 ref
low/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 al
lows 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 fol
lowing 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 fol
lowing 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 al
low 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 fol
lowing 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 al
lows). 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 al
lows 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 be
low. 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 al
low 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 fol
lowing 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 fol
lowed 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 be
low 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 al
low 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 al
lowing 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 be
low 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 be
low) type description frequency q gain
lowpass standard second-order resonant
lowpass filter with 12db/octave rolloff. frequencies be
low 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 fol
lows 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 fol
lowed by a space, fol
lowed 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 (#) fol
lowed 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 be
low 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 al
lowing 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_al
lowed_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_al
lowed_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_al
lowed_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_al
lowed_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_al
lowed_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_al
lowed_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_al
lowed_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_al
lowed_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_al
lowed_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_al
lowed_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_al
lowed_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_al
lowed_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_al
lowed_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_al
lowed_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_al
lowed_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 be
low). the examples be
low 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 be
low 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 al
low 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 al
lows 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
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 fol
lows (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 fol
lowing 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 fol
low 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 fol
lows, 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 fol
lowing 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 be
low. 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 al
lowed 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 be
low. 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 fol
lows. 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 be
low, 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 be
low, 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 al
low 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 be
low 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 f
low 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 f
low. 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 be
low 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 be
low. 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
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 al
lowed value. the clamp() function can be used anywhere a <length>, <frequency>, <angle>, <time>, <percentage>, <number>, or <integer> is al
lowed. 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, al
lows you to set a font-size that grows with the size of the viewport, but doesn't go be
low 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, fol
lowed 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 fol
lows 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 fol
lows it. the fol
lowing two gradients are equivalent. linear-gradient(red, orange, yel
low, green, blue); linear-gradient(red 0%, orange 25%, yel
low 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 al
low you to do the fol
lowing: 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 fol
lowed, 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 al
lows 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 be
low. 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 fol
lowing 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 be
low 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 al
low 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
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. al
lowed values are the same as the global lang attribute. ping a space-separated list of urls. when the link is fol
lowed, 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 fol
lowing 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
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 f
low 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
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 fol
lowing: 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 f
low 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
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 be
low, 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 fol
lowing 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 fol
low 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 al
low 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 fol
lowed 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 al
lowed 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 al
low 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 al
low 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 al
lowed 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 fol
lowing: <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: al
lows 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: al
lows mediastream: uris to be used as a content source. blob: al
lows blob: uris to be used as a content source. filesystem: al
lows 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 al
lowed 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 al
lows or prevents cross-origin frames from using fullscreen mode. this includes same-origin frames. if both this directive (i.e. via the al
low attribute) and the al
lowfullscreen attribute are present on an <iframe> element, this directive takes precedence. there was a bug whereby the fullscreen directive didn't work unless the al
lowfullscreen 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 al
low attribute) and the al
lowfullscreen attribute are present on an <iframe> element, this directive takes precedence. there was a bug whereby the fullscreen directive didn't work unless the al
lowfullscreen attribute was also present, but this has been fixed as of firefox 80 (bug 1608358). syntax feature-policy: fullscreen <al
lowlist>; <al
lowlist> an al
lowlist is a list of origins that takes one or more of the fol
lowing values, separated by spaces: *: the feature will be al
lowed 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 <al
lowlist>; <al
lowlist> an al
lowlist is a list of origins that takes one or more of the fol
lowing values, separated by spaces: *: the feature will be al
lowed in this document, and all nested browsing contexts (iframes) regardless of their origin. 'self': the feature will be al
lowed in this document, and in all nested browsing contexts (iframes) in the same origin. 'src': (in an iframe al
low attribute only) the feature will be al
lowed 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 al
lowed 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 al
lowed 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 al
lowed 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 <al
lowlist>; <al
lowlist> an al
lowlist is a list of origins that takes one or more of the fol
lowing values, separated by spaces: *: the feature will be al
lowed 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 be
low. ...
...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 be
low. ...
... 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 fol
lowing 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 fol
lowing: 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 al
low 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 al
low 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 al
lows 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 be
low.) 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, be
low.) 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 fol
lowing example illustrates an alternative approach, using foreach(). the fol
lowing 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 fol
lowing 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 fol
lowing code at the beginning of your scripts, al
lowing 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 fol
lowing: // object.defineproperty(a, k, { // value: mappedvalue, // writable: true, // enumerable: true, // configurable: true // }); // for best browser support, use the fol
lowing: 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 be
low). 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 fol
lowing 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 fol
lows: 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 be
low. the ctrz function be
low 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 be
low 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 al
lows 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, be
low, 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 fol
lowing 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 fol
lowing: 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 fol
lowing 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 fol
lowing
low surrogate'; } var next = str.charcodeat(i + 1); if (0xdc00 > next || next > 0xdfff) { throw 'high surrogate without fol
lowing
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 stackoverf
low. 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 fol
lowing 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 fol
lowing 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
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. al
lowed 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). al
lowed 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. al
lowed 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 al
lowing 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 al
lowing 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 fol
lowing 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 be
low). 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 fol
lowing 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. fol
lowing <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 al
lows 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 al
low each instance to have their own state, whereas member functions are properties that al
low instances to have behavior. inheritance al
lows 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 fol
lows: 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 fol
lowing: 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 s
low, so for the time being it's much easier to use the technique described be
low. 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 fol
lowed 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 fol
low. 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 fol
lowing 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 be
low 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 be
low. 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 fol
lowing 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 al
lows 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. fol
lowing 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 be
low. 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 al
low 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 fol
lowing 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 al
lows 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 s
low to fill in. the rule tree al
lows sharing. to al
low 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 ref
low). 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
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 be
low. 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 be
low. 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 fol
lowing 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 al
low 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 fol
low 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 al
low 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 fol
lowed up with semi-automated landings on tracemonkey and tamarin-redux. ...
... in tamarin-redux. we land patches initially in nanojit-central, and those landings are fol
lowed up with semi-automated landings on tracemonkey and tamarin-redux. these fol
low-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 fol
lowing 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::ref
low. the overload of the initialize and balancecolumnwidths routines depends on the table style and is decided at runtime. on the first ref
low 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 ref
low 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 fol
lowing the basic table layout strategy is discussed. the functionality is distributed over a large number of subroutines as shown in the chart be
low. ...
...d initialized (basictablelayoutstrategy::initialize). later the column widths are balanced by basictablelayoutstrategy::balancecolumnwidths or the fixed layout counter part. in the fol
lowing the basic table layout strategy is discussed. the functionality is distributed over a large number of subroutines as shown in the chart be
low. the words the table layout is width oriented and knows the fol
lowing 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 be
low the phase table shows all phases at the top of the page, each slave is shown as a box with a red,green, or yel
low color: red means failed, green passed, and yel
low has warnings. ...
... waterfall table be
low the phase table shows all phases at the top of the page, each slave is shown as a box with a red,green, or yel
low color: red means failed, green passed, and yel
low 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 fol
lowing filetypes ('.cpp', '.h', '.as', '.abs', '.py') for the fol
lowing: 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 fol
lowing: 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 fol
lowing 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 fol
lowing 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 fol
lowing: (?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 fol
lowing: <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, fol
lowing 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 al
lows 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 al
lows the conditions can be simpler. it also al
lows a common technique where the last rule in a template has no conditions, al
lowing 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 be
low, 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 fol
lowing 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 fol
lowing 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 fol
low 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 fol
lowing the arrows forward. or, you could start at d and fol
low two arrows back (and only fol
lowing 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 al
lows 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 al
lows 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 al
low 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 fol
lows: <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 be
low 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 fol
lowing 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 be
low 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 fol
lowing: (if you are using firefox 1.5 or later, see manifest files instead of be
low) 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 al
low 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 be
low. the install script should take the fol
lowing 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 fol
lowing 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 be
low, 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 fol
lowing 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 be
low. 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 al
lows these sections to be resized. you can place a splitter anywhere you want and it will al
low 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 al
low resizing horizontally. when a splitter is placed inside a vertical box, it will al
low 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 be
low) 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 al
lows 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 be
low 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", al
lows 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 al
low 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 al
lowed 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 al
low 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> al
lows 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 be
low. 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 al
lowed to access the chrome above it. content-primary the primary browser for content. the content that is loaded inside the browser is not al
lowed 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
« 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. al
lowevents 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 be
low 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 fol
lowing 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 yel
low 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
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 fol
lowing 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 fol
low 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 fol
low 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 fol
lowing 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. fol
low 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 (fol
lowing ac_add_app_options to that of your app. do the same with the name that fol
lows --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 fol
lowing 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 be
low) 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 fol
lowing 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 be
low 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 fel
lowship 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 be
low 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 fol
lowing 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 fol
lowing 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 fol
low. 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. fol
lowup 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 al
lowing us to build 3d vr landscapes using a system familiar to web developers, which fol
lows 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 fol
low 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. fol
low 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 be
low 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 fol
lowing 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 be
low 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 al
low 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 fol
low a character — like in platformers or rpgs — or al
low 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 fol
lowing 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, be
low 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 fol
lowing function to your code, be
low 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 fol
lowing 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 be
low: 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 al
low 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 be
low), xinclude can also target just specific portions of a document for inclusion. firefox does not support it natively, but the fol
lowing function aims to al
low its use with documents passed into it. code sample the fol
lowing 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 fol
lowing 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 al
low 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 al
lowed if (href === '' || href === null) { // points to same document if empty (null is equivalent to empty string) href = null; // set for uniformity in testing be
low 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, al
lowing 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 fol
low 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 fol
lowing 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 be
low: 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 fol
lowing 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 be
low. 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 be
low 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 fol
lowing 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 be
low, 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 be
low. ...
...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 be
low. ...
...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 be
low. 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 fol
lowing 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 fol
lowing 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 al
lows 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 workf
low. github has a very useful feature called github pages, which al
lows 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 fol
lowing 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 be
low 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%; overf
low : hidden; white-space : nowrap; text-overf
low : 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 */ overf
low-y: auto; overf
low-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%; overf
low : hidden; white-space : nowrap; text-overf
low : 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 al
lows 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 al
low 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 al
lows 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 be
low, 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 be
low, 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 be
low 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 fol
lows: 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 be
low, 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 be
low, 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 be
low, 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 be
low, 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 be
low 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 be
low, 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 be
low, 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 be
low, 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 be
low, 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 be
low 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 be
low. 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 be
low. 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 fol
low. 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 fol
lowing 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 al
lows 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 fol
lowing 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 be
low). 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 al
lows 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 be
low). 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 fol
lowing 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 be
low, 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 fol
lowing 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 al
lowed 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 s
low 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 fol
lowing 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, al
lowdelayedload 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); al
lowdelayedload if the message manager is a global frame message manager or a window message manager then: if al
lowdelayedload 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 al
lowdelayedload 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 al
lowdelayedload 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 fol
lowing 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, fol
lowed 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 fol
lowing 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 workf
lows are divided into these groups: mozilla applications, mozilla websites, and add-ons. be
low you'll find the list of all mozilla projects, their associated l10n tools, and links to tutorials outlining their workf
lows. mozilla applications so you're interested in localizing mozilla applications. each l10n tool fol
lows a different workf
low 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 fol
lowing 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 be
low 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 fol
lowing program. perl tools/bloatview/bloattable.pl log1 log2 ... logn > htmlfile this will produce an html file that contains a table similar to the fol
lowing (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 fol
low-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 s
low 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 al
lows 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 fol
lowing: 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 fol
lows 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 fol
lows, 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 fol
lows 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 fol
lowing 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_al
lowed (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
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 al
low 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 fol
lowing 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 fol
lows: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, fol
lowed 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 fol
lowing 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 fol
lowing 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, fol
lowed 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 fol
lowing 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 fol
lowing 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 fol
lows: 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 fol
lowing: -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, fol
lowed 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 fol
lowing 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 fol
lowing 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
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, fol
lowed 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 fol
lowing 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 fol
lowing 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 al
lows 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 al
lows 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 al
low "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 al
low 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 al
lowed 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 al
lowed to run. done naively, this technique can lead to reachable object not being marked. consider the fol
lowing 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 be
low 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 be
low. 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 fol
lowing 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 be
low. 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 s
low 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 fol
lowing: "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 be
low. 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 be
low 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 be
low 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 be
low. // 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 fol
lowing: 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 al
lowing 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 al
lows javascript code to access xpcom objects (i.e., it wraps native xpcom objects for javascript) and it al
lows 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 al
lowed values are stored in nsiabprefermailformat. ismaillist boolean maillisturi string if ismaillist is true then maillisturi will contain the uri of the associated mailing list. al
lowremotecontent boolean al
low 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 al
lows 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 al
lows 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 fol
lows: 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 fol
low 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 fol
low 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 aal
lowsamedocument); astring droplink(in nsidomdragevent aevent, out astring aname, [optional] in boolean adisal
lowinherit); void droplinks(in nsidomdragevent aevent, [optional] in boolean adisal
lowinherit, [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 be
low 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.f
lowers" 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 disal
lowed 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 al
lowport(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 al
lowed 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 al
lowed 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.al
lowregisterfromdifferenthost to true. examples register a webmail service as mailto handler the fol
lowing code aims to add "outlook.com live mail" to list of webservice handlers. in the image be
low "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.al
lowregisterfromdifferenthost 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 al
lowregisterfromdifferenthost = 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 al
lowregisterfromdifferenthost = services.prefs.getboolpref('gecko.handlerservice.al
lowregisterfromdifferenthost'); if (!al
lowregisterfromdifferenthost) { services.prefs.setboolpref('gecko.handlerservice.al
lowregisterfromdifferenthost', 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 be
low). 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 be
low 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 fol
lows: <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 al
lowed 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 al
lows 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 fol
lowing 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 al
lowed 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, al
lowing 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 fol
lowing 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, fol
lowed by either a decimal number or "0x" or "0x" fol
lowed 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, fol
lowed by either a decimal number or "0x" or "0x" fol
lowed 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 al
lowing 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 al
lowing 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 al
lows 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 be
low return placeholder values. convention for descriptions of properties and methods be
low, 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 fol
lowing 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 al
lowwasmbinarysource property set, the "[wasm]" value will be returned in this case. binary if the instance refers to webassembly code and the debugger has the al
lowwasmbinarysource 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 shal
low 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 shal
low 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 "shal
low 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 al
low 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 fol
lowing 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 fol
lowing 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 fol
lowing: in firefox 76 and above, the message can look like the fol
lowing: 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 be
low: this firefox the this firefox tab combines the features of extensions, tabs, and workers into a single tab with the fol
lowing 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 fol
lowing 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 fol
lowing 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 al
low 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 fol
lowing 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 be
low: 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 fol
lows: 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, al
lowing 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 al
lows 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 al
lows 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 fol
lowing 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 be
low. ...
...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 be
low. 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 be
low. html in the html for this example, shown be
low, 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 be
low. they're not crucial to the concept shown in the html above, but you may expand the view be
low if you wish to read the css used. view the css editors: if you change the css be
low, 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 fol
lowing 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 al
lowed if the cell is in a column group. row the header cell applies to the fol
lowing 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 al
low 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 fol
lowed 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 fol
lowing: 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 fol
lowing 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 s
lowing 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 fol
lowing: 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 al
lows 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 fol
lowing properties: attribute description unique if true, the index will not al
low 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 fol
lowing constants. keyboard locations the fol
lowing 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 fol
lowing 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. al
lowed 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 al
lows 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 be
low). the permissions api provides the tools to al
low 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 — be
low 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 al
low 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 be
low 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 be
low 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 be
low 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 fol
lowing 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_al
lowed_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_al
lowed_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_al
lowed_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_al
lowed_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 al
lows 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, fol
lowing 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 al
lows 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 al
lows 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 fol
lowing 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 fol
lowing 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 al
low 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 fol
lowing 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 al
lowed 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 al
low 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 fol
lowing 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 fol
low 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 fol
lowing 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 fol
lowing: 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
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 be
low 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 fol
lowing features are just a condition for whether to open popup or not. see popup condition section. the fol
lowing 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 al
lowing 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 al
low 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 al
low 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 fol
lowing 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 fol
lowing 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 al
lows 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 be
low 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 be
low 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 fol
lows (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 be
low, 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 al
low 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). be
low 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 fol
low 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 be
low 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 be
low. 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 be
low. 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 be
low. 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
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 al
low 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 al
low 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 overf
low-block how does the output device handle content that overf
lows the viewport along the block axis? added in media queries level 4. overf
low-inline can content that overf
lows 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 fol
lowing. however, css pre-processors simply generate valid css, so the techniques used be
low 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 be
low 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 f
low 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 f
low 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 fol
lowing 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 fol
lowing 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 be
low, 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 be
low, 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 f
lowing 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 be
low 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 fol
lows the direction and writing-mode. example: inset properties for positioned layout positioning generally al
lows 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 f
low. 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 be
low 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 be
low 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 be
low 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 be
low 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
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 al
lows 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 al
lows 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 al
low you to define configurations of style, as keyframes, and to transition between them defining an animation. css transitions css3 transitions al
low you to define an animation between several styles and to control the way this transition happens. css transforms transforms al
low you to change the position of elements by modifying their coordinate space: it al
lows 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 al
low 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; /* overf
low 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 overf
low 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
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 fol
lowing 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: al
low-end; /* two keywords */ hanging-punctuation: first force-end; hanging-punctuation: first al
low-end; hanging-punctuation: first last; hanging-punctuation: last force-end; hanging-punctuation: last al
low-end; /* three keywords */ hanging-punctuation: first force-end last; hanging-punctuation: first al
low-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 be
low. 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 overf
low-anchor, as described be
low. what if i need to disable it? the specification provides a new property, overf
low-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, fol
lowed 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 fol
lows 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 yel
low. repeating-conic-gradient(from 0deg, red 0deg 30deg, yel
low 30deg 60deg, blue 60deg 90deg); repeating-radial-gradient(red 0 8%, yel
low 8% 16%, blue 16% 24%); conic-gradient(red 120deg, yel
low 120deg 240deg, blue 240deg); radial-gradient(red 33%, yel
low 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 overf
low property to determine whether to clip any overf
lowing content, but only if the table has a known width; otherwise, they won't overf
low 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 f
low direction, which is the direction in which block-level containers are stacked, and the direction in which inline-level content f
lows 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 f
lows 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 be
low. the f
low 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 f
lows horizontally from left to right. for rtl scripts, content f
lows horizontally from right to left. the next horizontal line is positio...
...f
low 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 f
lows horizontally from left to right. for rtl scripts, content f
lows horizontally from right to left. the next horizontal line is positioned be
low the previous line. vertical-rl for ltr scripts, content f
lows vertically from top to bottom, and the next vertical line is positioned to the left of the previous line. for rtl scripts, content f
lows 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, ref
low 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 f
low from the original browser f
low 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 f
low, 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 fol
low the be
low 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
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 fol
low-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 al
lows 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 f
low 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 workf
low the fol
lowing diagram illustrates the typical workf
low 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 fol
lowing 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 be
low). 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
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
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 fol
lowing 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 be
low. 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 al
lowed (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 be
low: <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
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 al
lows 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 al
low 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 al
lowed in these elements not al
lowed 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 al
lows 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, al
lowing 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, fol
lowing 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 al
lowed 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 fol
lowing: <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: al
lows 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: al
lows mediastream: uris to be used as a content source. blob: al
lows blob: uris to be used as a content source. filesystem: al
lows filesystem: uris to be used as a content source. 'self' refers to the origin fr...
...urce. blob: al
lows blob: uris to be used as a content source. filesystem: al
lows 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 al
low these content types can specify them using the data attribute. 'unsafe-eval' al
lows the use of eval() and similar methods for creating code from strings. you must include the single quotes. 'unsafe-hashes' al
lows 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 al
lows 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 fol
lowing: the frame-ancestors directive’s syntax is similar to a source list of other directives (e.g. default-src), but doesn't al
low '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 fol
lowing: the frame-ancestors directive’s syntax is similar to a source list of other directives (e.g. default-src), but doesn't al
low 'unsafe-eval' or 'unsafe-inline' for example. it will also not fall back to a default-src setting. only the sources listed be
low are al
lowed: <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 al
lowed 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 fol
lowing: <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: al
lows 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: al
lows mediastream: uris to be used as a content source. blob: al
lows blob: uris to be used as a content source. filesystem: al
lows filesystem: uris to be used as a content source. 'self' refers to the origin fr...
...urce. blob: al
lows blob: uris to be used as a content source. filesystem: al
lows 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 al
low these content types can specify them using the data attribute. 'unsafe-eval' al
lows the use of eval() and similar methods for creating code from strings. you must include the single quotes. 'unsafe-hashes' al
lows 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 al
lowed 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 fol
lowing: <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: al
lows 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: al
lows mediastream: uris to be used as a content source. blob: al
lows blob: uris to be used as a content source. filesystem: al
lows filesystem: uris to be used as a content source. 'self' refers to the origin fr...
...urce. blob: al
lows blob: uris to be used as a content source. filesystem: al
lows 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 al
low these content types can specify them using the data attribute. 'unsafe-eval' al
lows the use of eval() and similar methods for creating code from strings. you must include the single quotes. 'unsafe-hashes' al
lows 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 al
lowed 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 fol
lowing: <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: al
lows 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: al
lows mediastream: uris to be used as a content source. blob: al
lows blob: uris to be used as a content source. filesystem: al
lows filesystem: uris to be used as a content source. 'self' refers to the origin fr...
...urce. blob: al
lows blob: uris to be used as a content source. filesystem: al
lows 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 al
low these content types can specify them using the data attribute. 'unsafe-eval' al
lows the use of eval() and similar methods for creating code from strings. you must include the single quotes. 'unsafe-hashes' al
lows 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 al
low 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 al
low-list of trusted types policies. trusted types al
lows 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 al
lowed 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 <al
lowlist>; <al
lowlist> an al
lowlist is a list of origins that takes one or more of the fol
lowing values, separated by spaces: *: the feature will be al
lowed in this document, and all nested browsing contexts (iframes) regardless of their origin. 'self': the feature will be al
lowed 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 al
lowed 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 <al
lowlist>; <al
lowlist> an al
lowlist is a list of origins that takes one or more of the fol
lowing values, separated by spaces: *: the feature will be al
lowed in this document, and all nested browsing contexts (iframes) regardless of their origin. 'self': the feature will be al
lowed 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 al
lowed to use the payment request api. when this policy is disabled, the paymentrequest() constructor will throw a syntaxerror. syntax feature-policy: payment <al
lowlist>; <al
lowlist> an al
lowlist is a list of origins that takes one or more of the fol
lowing values, separated by spaces: *: the feature will be al
lowed in this document, and all nested browsing contexts (iframes) regardless of their origin. 'self': the feature will be al
lowed 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 al
lowed 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 <al
lowlist>; <al
lowlist> an al
lowlist is a list of origins that takes one or more of the fol
lowing values, separated by spaces: *: the feature will be al
lowed in this document, and all nested browsing contexts (iframes) regardless of their origin. 'self': the feature will be al
lowed 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 al
lowed 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 <al
lowlist>; <al
lowlist> an al
lowlist is a list of origins that takes one or more of the fol
lowing values, separated by spaces: *: the feature will be al
lowed in this document, and all nested browsing contexts (iframes) regardless of their origin. 'self': the feature will be al
lowed 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 al
lowed 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 <al
lowlist>; <al
lowlist> an al
lowlist is a list of origins that takes one or more of the fol
lowing values, separated by spaces: *: the feature will be al
lowed in this document, and all nested browsing contexts (iframes) regardless of their origin. 'self': the feature will be al
lowed 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 al
lowed 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 al
lowed 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 <al
lowlist>; <al
lowlist> an al
lowlist is a list of origins that takes one or more of the fol
lowing values, separated by spaces: *: the feature will be al
lowed 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 <al
lowlist>; <al
lowlist> an al
lowlist is a list of origins that takes one or more of the fol
lowing values, separated by spaces: *: the feature will be al
lowed in this document, and all nested browsing contexts (iframes) regardless of their origin. 'self': the feature will be al
lowed in this document, and in all nested browsing contexts (iframes) in the same origin. 'src': (in an iframe al
low attribute only) the feature will be al
lowed 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 fol
lowing: ( ) < > @ , ; : \ " / [ ] ? = { }. 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 al
lowed 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 al
lowed, 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 fol
lows: <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 fol
low: <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 al
lows 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
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 fol
lowed 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 fol
low the same basic structure of an http header: a case-insensitive string fol
lowed 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 be
low). 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 be
low). 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 fol
lowing 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 fol
lowed 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 fol
lowed 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 fol
lowed by "n" which is a word character. /oon\b/ matches the "oon" in "moon", because "oon" is the end of the string, thus not fol
lowed by a word character. /\w\b\w/ will never match anything, because a word character can never be fol
lowed 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 be
low. 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 shal
low copy of the existing array on which it is called. see the description be
low 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, fol
lowed 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, fol
lowed 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 shal
low 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 fol
lows: 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 fol
lowing code at the beginning of your scripts, al
lowing 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 shal
lowcopy = 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 fol
lows 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 fol
lowing 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 fol
lowed 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 al
lowed 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 fol
lowing output: thetree.constructor is function tree(name) { this.name = name } changing the constructor of an object the fol
lowing 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 al
lows 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 al
lows 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 fol
lowing 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 fol
lowing 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 be
low 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 fol
lowing meanings: "nfc" canonical decomposition, fol
lowed by canonical composition. "nfd" canonical decomposition. "nfkc" compatibility decomposition, fol
lowed 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) fol
lowed 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 fol
lowing 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 fol
lowing 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 fol
lowed by its operand: typeof operand typeof(operand) parameters operand an expression representing the object or primitive whose type is to be returned. description the fol
lowing 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 fol
lowing 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 al
lowed 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, disal
lows 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 al
lows trailing commas in function parameter lists. parameter definitions the fol
lowing 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) al
lows 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 s
lower 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 fol
lows 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
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 be
low. 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 be
low). 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 be
low). 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 be
low for a list of al
lowed values. feature strings the fol
lowing 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 al
lowed 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 fol
lowing 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 al
lows you to: animate the numeric attributes of an element (x, y, ...) animate transform attributes (translation or rotation) animate color attributes fol
low a motion path this is done adding an svg element like <animate> inside the svg element to animate. be
low are examples for the four different ways. animating attributes of an element the fol
lowing 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 be
low, 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 al
lows 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 be
low). 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 be
low. 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 fol
lowing 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 be
low for details), <?xslt-param?> and <?xslt-param-namespace?>. both pis can contain "pseudo attributes" the same way that the xml-stylesheet pi does. the fol
lowing 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 fol
lows 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 fol
lowing 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 fol
lowing 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 fol
low 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 al
lows 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 fol
lowing 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 fol
lowing 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 fol
lowing 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. al
low object an object with keys to configure the permissions on the page worker. the boolean key script controls if scripts from the page are al
lowed 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 be
low. 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 be
low 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 fol
lowing 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 fol
lowing 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. al
low object permissions for the content, with the fol
lowing 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 be
low, 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 fol
lowing 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 fol
lowing 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 fol
low 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 fol
lowing 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="overf
low: 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 fol
lowing 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 al
lowed 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 al
low 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 fol
lowing 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 fol
lowing 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 al
lows 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 al
lows 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, al
lowing 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 al
low 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, al
lowing 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 fol
lowing page contains examples of many promise-based replacement apis for common operations. these apis al
low asynchronous operation to be achieved with a coding style similar to synchronous variants. the fol
lowing 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 al
low asynchronous operation to be achieved with a coding style similar to synchronous variants. the fol
lowing 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 fol
lowing example relies on the helper function defined be
low. 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 fel
lowship 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 ref
low 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 al
low 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 fol
lowing 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 fol
lowing 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 fol
lowing: snavigator. this triggers a splash screen, fol
lowed by a "source-navigator projects" dialog as the fol
lowing: i've already created a new project bin.proj before documenting this. ...
...execute the fol
lowing: snavigator. this triggers a splash screen, fol
lowed by a "source-navigator projects" dialog as the fol
lowing: 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 al
lows 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 al
low 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 be
low 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 be
low: 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 fol
lowing 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 fol
low 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 fol
lowing 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 fol
lowing 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 al
lows us to, for example, work with the places database without affecting its contents. private browsing notifications there are notifications available that al
low 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 al
lows programmers to take advantage of the nsstring/nsstrimpl implementation, while eliminating heap based allocations. an additional improvement has been made to nsautostring that al
lows 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 al
low 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 yel
low letter "f". a second click will remove the future breakpoint as well. advanced breakpoints venkman al
lows 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 fol
lowing 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, al
lowing 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 al
lows 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 f
low 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 f
low. 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 f
low. xbl event handlers always fire last, after all other event handlers at the same position in the event f
low. since xbl handlers usually constitute the default actions for a widget, this al
lows 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 fol
lowing 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 be
low 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 be
low 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 fol
lowing 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 fol
lowing: <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 fol
lowing 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 al
lows 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 al
lows 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 fol
lowing 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 fol
lowing 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, fol
lowed 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 al
lows 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 fol
lowing: 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 be
low 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 be
low that. templates have a means of al
lowing 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 fol
lowing: 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 al
lows 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 fol
lowing 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 fol
lows: <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 be
low: 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 fol
lowing 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 fol
lowing 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 al
lows 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 be
low. 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 fol
lows: 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 fol
lowing: <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 be
low: 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 fol
lowing 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 be
low 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 be
low. 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 fol
lowing 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 al
lows. 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 fol
lowing 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 be
low 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 be
low, 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, al
lowing 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 fol
lowing 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 be
low 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 al
low the 'skin' (in this case, the appearance of the image) to be changed without changing the xul file. an example is shown be
low. 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 be
low 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 be
low. in this case, the dir attribute controls the placement above or be
low. the same values are used, where normal means place the image above the text, and reverse means place the image be
low 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 al
lowed and are just ignored if typed. in addition, arrow buttons appear beside the textbox to al
low 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 fol
lowing 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 al
lows the number to change by a larger amount. for instance, the fol
lowing 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 be
low shows the resources (or fields) that you can retrieve from the history datasource. put the url values be
low 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 be
low. 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 al
low 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 al
lows 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 fol
lowing: <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. be
low 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 al
lows 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 al
lowed 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
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 al
lowed 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 be
low 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 al
lowed 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 be
low 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 fol
lowing 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 al
lowed 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 be
low 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 fol
lowing 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 al
lowed 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
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 fol
lowing 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 be
lowthe 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.s
lowthe panels s
lowly 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 be
low 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 al
lowed 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 be
low: 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 fol
lowing 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 fol
lowing 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 be
low 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 fol
lowing 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 be
low 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 fol
lowing 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
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="yel
low" 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 be
low 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 fol
lowing 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; overf
low: 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 be
low 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 be
low 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 fol
lowing 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 fol
lowing 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 fol
low 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 fol
low 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 fol
lowing 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 fol
lowing 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 fol
low 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 fol
low 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 fol
lowing 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 fol
lowing 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 fol
low 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 fol
low 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 fol
lowing 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 fol
lowing 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 fol
low 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 fol
low the directions. linux unpack the tarball to a new directory using tar -xjf xulrunner-3.6.26.en-us.linux-i686.tar.bz2. the fol
lowing 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 fol
lowing 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 fol
low 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 fol
low 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 fol
lowing 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 be
low 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 fol
lowing 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 be
low. 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 fol
lowing 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 fol
lowed 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 overf
low 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 al
lows 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 al
low 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 fol
low 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 fol
low 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 nshtmlref
lowstate(computeblockboxdata, initconstraints) and nsimageframe::getdesiredsize which uses ns_inrinsicsize, into the fol
lowing method: /** * compute the size that a frame will occupy. called while * constructing the nshtmlref
lowstate to be used to ref
low 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 nshtmlref
lowstate. discussion on how to determine whether there is pending layout changes or ref
lows when using a popup. it was concluded that a frame model change is utilized within a popup, not a layout change. on the ref
low 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 fol
low strict rules when authoring xhtml. in particular: raw < and & characters are not al
lowed 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 al
lowed 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: yel
low;} --> </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 fol
low 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 s
low 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 fol
lowing 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 fol
lowing 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 fol
lowing: 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 al
low 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 al
lowed 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 fol
lowing 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 al
low 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 al
lows 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 fol
lowing: 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 al
low for the fol
lowing 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 fol
lowing 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 be
low 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 fol
lowing 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 fol
lowing 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 fol
low 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 al
low 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 fol
low 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 be
low if you're working with panasonic tvs running firefox os: you can add moving between states, starting a new game, controlling the ship and b
lowing 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 fol
lowing 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 fol
lowing new variables be
low 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 be
low 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 be
low 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 be
low, 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 be
low, 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 fol
lows a heading, as in my example be
low. 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 be
low 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 fol
lowing articles, which cover the most essential parts of the css language. along the way you'll come across plenty of exercises to al
low 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 al
low 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, al
lowing 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, al
lowing 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 fol
lows: 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. be
low 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 be
low, 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 be
low. try updating the live code be
low 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 be
low 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 be
low 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 be
low, 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 be
low, 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 be
low 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 be
low. try updating the live code be
low 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 fol
low 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 fol
lowing 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 fol
lows: .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 fol
lowing: 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 f
low 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 al
lowed 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 be
low 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 be
low 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 be
low), 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 fol
lowing 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, fol
low 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 fol
lowed 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 al
lowing 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 al
low 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 be
low for more details). anchors most links tie two webpages together. anchors tie two sections of one document together. when you fol
low 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 s
lows 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 fol
lowing 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 s
low 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 fol
lowing 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 al
low 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 al
low 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 fol
lowing 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 be
low, 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 be
low, 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 be
low 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 fol
lowing 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 al
low 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 be
low. ...
... 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 s
low 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 be
low 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 be
low), 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, al
lowing 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 fol
lowing 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 al
lowing them to control a user interface. in the articles listed be
low, 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 al
lows for automatic updates, you can fol
low 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 al
low 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 fol
lowing 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 al
lows for quick navigation to links and convenient text searching 2) browse with caret (f7 key toggles) al
lows 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 fol
low 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 fol
lows: ... @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 al
low 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 al
low 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 fol
lowing 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 fol
lowing 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 s
lower 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 fol
lowing 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 fol
lowing 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 fol
lowing 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, fol
lowing these recommendations will also help ensure your comments are extremely human-readable, too. don't worry! ...
...y to search and read documentation. but by fol
lowing 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 fol
lowing: /** * */ 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 s
lower 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 s
lower 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 s
lower 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 s
lows 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 be
low). 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 s
lows 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 be
low). 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 al
lows 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 al
low 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 be
low, 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 fol
lowed 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 fol
lowlinks); nsifile getdir(string key, array patharray, bool shouldcreate, bool fol
lowlinks); 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 fol
lowlinks ); 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. fol
lowlinks optional true if links should be fol
lowed, false otherwise. return value returns a nsifile object for the file specifi...
...wlinks optional true if links should be fol
lowed, 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 fol
lowlinks ); 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 be
low 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 be
low 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 fol
lowing 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 fol
lowing 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 fol
lowing attributes: version: which version of the source map spec this map is fol
lowing. 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 fol
lowing properties: line: the line number in the generated source. column: the column number in the generated source. and an object is returned with the fol
lowing 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 fol
lowing 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 fol
lowing 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 be
low. 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 be
low: 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 fol
lowing 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 be
low, 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 fol
lowing 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. al
lows us to understand how each l10n team is performing their localization work. al
lows 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 f
low 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 al
lowed 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 fol
lows: 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 fol
lowing 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 fol
lowing reasons. they are less error-prone. we've had m...
...decremented on each relevant deallocation. traversal-based reporters are preferable, for the fol
lowing 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 be
low 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 fol
lowing 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 fol
lowed. that said, note that for some classes these methods may be virtual.) mfbt/memoryreporting.h defines mozilla::mallocsizeof as fol
lows: 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 fol
lows. $objdir/dist/bin/rapl linux on linux, rapl can be run as root, as fol
lows. 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 al
low easy access to the relevant model-specific registers. output the fol
lowing 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 al
lows 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 al
low 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 al
low 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 be
low. 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 be
low. ...
...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_al
low_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 fol
low the format <label> <space> <clientrandom> <space> <secret> where: <label> describes the fol
lowing secret. <clientrandom> is 32 bytes random value from the client hello message, encoded as 64 hexadecimal characters. <secret> depends on the label (see be
low). ...
...2292. this key log file is a series of lines. comment lines begin with a sharp character ('#') and are ignored. secrets fol
low the format <label> <space> <clientrandom> <space> <secret> where: <label> describes the fol
lowing secret. <clientrandom> is 32 bytes random value from the client hello message, encoded as 64 hexadecimal characters. <secret> depends on the label (see be
low). ...
...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 be
low. 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 fol
lowing 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 overf
low 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 be
low. 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 fol
lowing 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 overf
low 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 be
low. 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 fol
lowing 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 overf
low 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 al
low 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 al
lows export clients to use strong crypto. certusagesslca ............... an intermediate or root ca cert al
lowed 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 be
low). 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 shal
low 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 shal
low 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 fol
lowing 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 be
low. 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 be
low 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 be
low, 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 al
low 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 fol
lowed 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 al
low out-parameters for rooted gcthings. this class solves two problems: c++ only al
lows 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 fol
lows: 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 f
low 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; jslocaleto
lowercase localeto
lowercase; jslocalecompare localecompare; // not used #if expose_intl_api jslocaletounicode localetounicode; }; typedef bool (* jslocaletouppercase)(jscontext *cx, js::handlestring src, js::mutablehandlevalue rval); typedef bool (* jslocaleto
lowercase)(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 be
low. 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 fol
lowing 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 be
low. 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 fol
lowing 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 be
low. 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 be
low. 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 fol
lowing 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 be
low. 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 al
lows configuration of the grouping and level of detail to be returned in the results. the different values for this property are listed be
low. 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 fol
lows 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 fol
lowing: 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 fol
low 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
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 al
low adding and removing members. nsimutablearray - a scriptable container for scriptable xpcom objects, which al
lows 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 al
lows 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 fol
lows 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 al
lows 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 be
low 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 fol
lowing 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 fol
low 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 fol
low 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 fol
lowing 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 fol
lowing 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 fol
lowing 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. fol
lowing 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. al
lowdrop() 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. al
lowdrop() will be called many times during drag so ensure that it is efficient. method overview boolean al
lowdrop(in nsidomevent event, in nsidragsession session); boolean al
lowstartdrag(in nsidomevent event); boolean oncopyordrag(in nsidomevent aevent, in nsitransferable trans); boolean onpasteordrop(in nsidomevent event, in nsitransferable trans); methods al
lowdrop() tells gecko whether a drop is al
lowed on this content area. boolean al
lowdrop( 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 al
lowundo); void copymessages(in nsimsgfolder srcfolder, in nsisupportsarray messages,in boolean ismove, in nsimsgwindow msgwindow,in nsimsgcopyservicelistener listener, in boolean isfolder, in boolean al
lowundo); 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 al
lows 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 al
lowsposting 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 aal
lowdelayedload) 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 aal
lowdelayedload 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 al
low 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 al
low 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 al
lowed 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 fol
lowing 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 al
lowable at the current location. to get the behavior where drops are only al
lowed 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 be
low 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 fol
lows: 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 fol
lowing: 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 fol
lowing 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 be
low. 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 al
lows 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 fol
lowing 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 be
low 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 fol
lows 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, fol
lowed 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 al
lows 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 be
low. note: the layout view can be found underneath the layout tab on the right-hand pane of the page inspector. the above and be
low 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 fol
lowing 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 "ref
low". 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 "ref
low". 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 al
lows 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 fol
lowing 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 fol
lows, where "bit 0" is the least significant bit and all bits not specifically mentioned be
low 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 fol
low the first 37 bytes of this authenticatordata. bit 7, extension data (ed) - if set, extension data is present. extension data will fol
low attestedcredentialdata if it is present, or will immediatelly fol
low 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 fol
lowing 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 fol
lowing 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 fol
lowing: 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 fol
lowing 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 al
low 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 fol
lowing 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 al
lows 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 al
lows developers to tell the browser about their specific offline content. this al
lows 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 al
lows 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 fol
lowing 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 fol
lowing 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 be
low indicate the legacy code value and constant name that were used in the past. indexsizeerror the index is not in the al
lowed 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) nomodificational
lowederror the object cannot be modified. (legacy code value: 7 and legacy constant name: no_modification_al
lowed_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 al
lowed 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
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 fol
lowing cookie attribute values can optionally fol
low 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 fol
lowing 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 disal
lowed 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 disal
lowed in cookie values). some user agent implementations support the fol
lowing 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 fol
lowing 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 fol
lowing: 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 fol
lowing 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: hel
loworld. 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 be
low, 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 fol
lowing 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
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 fol
lowing 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 al
low 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 --al
low-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 al
lowed. 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 al
lows 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 al
lows 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 fol
lowing 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 fol
lowing 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 al
low 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 al
lowed 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 fol
lowing 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> al
low 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 be
low, 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 fol
lowing 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 al
lows 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 effectal
lowed 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 fol
lowing 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) al
lows data to be read but not changed. read_write "readwrite" (1 in chrome) al
lows reading and writing of data in existing data stores to be changed. version_change "versionchange" (2 in chrome) al
lows 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 fol
lowing 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 fol
lowing: 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 stackoverf
low 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 fol
lowing 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
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 fol
lowing 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 fol
lowing 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 be
low 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 al
lows a web page to provide rich media metadata, for display in a platform ui. mediasession al
lows 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. be
low 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 fol
low 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 fol
lowing 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 fol
lowed 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 al
lowed. 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 be
low. 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 “al
low 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 be
low. ...
...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 fol
lowing 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 fol
lowing 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 be
low) 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 fol
lowing performanceentry properties for navigation performance entry types by qualifying and constraining them as fol
lows: 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 al
low 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 al
lowing 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 fol
lowing 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 be
low. 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
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 fol
lowing 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 al
lows 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, al
lowing 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 be
low, 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 be
low 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
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 fol
lowing 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: fol
low, error, or manual. the default is fol
low. 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
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 fol
low, 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 fol
lowing 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 fol
lowing example illustrates using the resource timing properties to calculate the amount of time the fol
lowing 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 fol
lowing 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 fol
lowing 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 al
low 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 al
low-storage-access-by-user-activation sandbox token. the embedding website needs to add this to al
low storage access requests to be successful, along with al
low-scripts and al
low-same-origin to al
low it to call the api, and execute in an origin that can have cookies: <iframe sandbox="al
low-storage-access-by-user-activation al
low-scripts al
low-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 al
lows 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 fol
lowed. 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 al
lows 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 al
lowing 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 al
lowing 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
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 fol
lowing 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 al
lows 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 fol
lowing 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 fol
lows 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 al
low 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 be
low: 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 disal
lowing 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 al
low 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 fol
lowing 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 fol
lowing 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 fol
lowing 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: fol
low (automatically fol
low redirects), error (abort with an error if a redirect occurs), or manual (handle redirects manually). in chrome the default is fol
low (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 al
low the request to outlive the page. fetch with the keepalive flag is a replacement for the navigator.sendbeacon() api. signal an abortsignal object instance; al
lows 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 fol
lowing: 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 be
low 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 al
lows 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 fol
lowing 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 fol
lows 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 al
lows 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 be
low the origin. on the web, the default origin is the top-left corner of a given context (with positive y-coordinate values being be
low 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 be
low. 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 be
low. 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 be
low, 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 f
low 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 be
low, 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, fol
lowed 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 al
low 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-f
low.” - 3. flex containers in the fol
lowing 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 al
low 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 fol
lows: 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 be
low, 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 be
low 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 be
low 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 fol
lowing 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-overf
low-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 fol
lows: 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 al
lowable 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 fol
low 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 fol
low 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 be
low 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 f
low. ...
... defined by these values. in all of the examples be
low 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 f
low. 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 be
low, 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 f
lowing 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-f
low-from -ms-f
low-into -ms-high-contrast-adjust -ms-hyphenate-limit-chars -ms-hyphenate-limit-lines -ms-hyphenate-limit-zone -ms-ime-align -ms-overf
low-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
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 al
lowed 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 be
low. 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 overf
lows 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 overf
low 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 overf
low 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 overf
lows 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 al
lowing 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, s
lowing 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, s
lowing 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 s
lowly, 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, s
lowing down the animation continues. • ease-in-out equal to cubic-bezier(0.42, 0, 0.58, 1.0), with the animating properties s
lowly transitioning, speeding up, and then s
lowing 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 fol
lowing 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
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 fol
lowing 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; overf
low: 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 be
low. ...
...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 fol
low 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
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 al
lowed. the source for this interactive example is stored in a github repository. if 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 fol
lowing 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 fol
lowed by a negative length — an invalid expression — while calc(50% - 8px) is a percentage fol
lowed by a subtraction operator and a length. likewise, calc(8px + -50%) is treated as a length fol
lowed by an addition operator and a negative percentage. the * and / operators do not require whitespace, but adding it for consistency is both al
lowed 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: yel
low; 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: f
low the element lays out its contents using f
low layout (block-and-inline layout). ...
...syntax valid <display-inside> values: f
low the element lays out its contents using f
low 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 overf
low) 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. f
low-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 be
low 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 fol
lowing 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 overf
lows 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 overf
low 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 fol
low 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 fol
low. 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 fol
lows 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 fol
lows 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 be
low 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 al
lowing 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, s
lowing 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, s
lowing 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 s
lowly, with the transition speed increasing until complete. ease-out equal to cubic-bezier(0, 0, 0.58, 1.0), starts transitioning quickly, s
lowing down the transition continues. • ease-in-out equal to cubic-bezier(0.42, 0, 0.58, 1.0), starts transitioning s
lowly, speeds up, and then s
lows 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 fol
lowing 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 al
lows 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" al
lows 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 al
lows 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 al
low 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 fol
lowing 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 al
lowed 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 fol
lowing 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 be
low 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
this interactive example is stored in a github repository. if 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 f
low content, palpable content permitted content f
low content, but not containing <form> elements tag omission none, both the starting and ending tag are mandatory. permitted parents any element that accepts f
low 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
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, al
lowing 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 fol
lowing 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
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 fol
lowing: 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 al
lowed values are names of particular http headers: content-security-policy al
lows page authors to define a content policy for the current page. content policies mostly specify al
lowed 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 al
lows 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 fol
lows. 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 fol
lowing 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 fol
lowing. 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 al
low 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 al
lows 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 al
lows 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
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 be
low, 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 al
lowed 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 fol
lowing 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 al
lowed 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 fol
lowing: <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: al
lows 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: al
lows mediastream: uris to be used as a content source. blob: al
lows blob: uris to be used as a content source. filesystem: al
lows filesystem: uris to be used as a content source. 'self' refers to the origin fr...
...urce. blob: al
lows blob: uris to be used as a content source. filesystem: al
lows 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 al
low these content types can specify them using the data attribute. 'unsafe-eval' al
lows the use of eval() and similar methods for creating code from strings. you must include the single quotes. 'unsafe-hashes' al
lows 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 al
lows 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 disal
lowing plugins to disal
low all plugins, the object-src directive should be set to 'none' which will disal
low 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 disal
lowing plugins to disal
low all plugins, the object-src directive should be set to 'none' which will disal
low plugins. the plugin-types directive is only used if you are al
lowing plugins with object-src at all. ...
...olicy: plugin-types <type>/<subtype> <type>/<subtype>; <type>/<subtype> a valid mime type. examples disal
lowing plugins to disal
low all plugins, the object-src directive should be set to 'none' which will disal
low plugins. the plugin-types directive is only used if you are al
lowing 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 al
lowed 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 fol
lowing: <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: al
lows 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: al
lows mediastream: uris to be used as a content source. blob: al
lows blob: uris to be used as a content source. filesystem: al
lows filesystem: uris to be used as a content source. 'self' refers to the origin fr...
...urce. blob: al
lows blob: uris to be used as a content source. filesystem: al
lows 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 al
low these content types can specify them using the data attribute. 'unsafe-eval' al
lows the use of eval() and similar methods for creating code from strings. you must include the single quotes. 'unsafe-hashes' al
lows 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 fol
lowing 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 fol
lowing policy, disal
lowing 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 al
lowed to gather information about the acceleration of the device through the accelerometer interface. syntax feature-policy: accelerometer <al
lowlist>; <al
lowlist> an al
lowlist is a list of origins that takes one or more of the fol
lowing values, separated by spaces: *: the feature will be al
lowed in this document, and all nested browsing contexts (iframes) regardless of their origin. 'self': the feature will be al
lowed 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 al
lowed to gather information about the amount of light in the environment around the device through the ambientlightsensor interface. syntax feature-policy: ambient-light-sensor <al
lowlist>; <al
lowlist> an al
lowlist is a list of origins that takes one or more of the fol
lowing values, separated by spaces: *: the feature will be al
lowed in this document, and all nested browsing contexts (iframes) regardless of their origin. 'self': the feature will be al
lowed 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 al
lowed to gather information about the acceleration of the device through the batterymanager interface obtained via navigator.getbattery(). syntax feature-policy: battery <al
lowlist>; <al
lowlist> an al
lowlist is a list of origins that takes one or more of the fol
lowing values, separated by spaces: *: the feature will be al
lowed in this document, and all nested browsing contexts (iframes) regardless of their origin. 'self': the feature will be al
lowed 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 al
lowed to use video input devices. when this policy is enabled, the promise returned by mediadevices.getusermedia() will reject with a notal
lowederror. syntax feature-policy: camera <al
lowlist>; <al
lowlist> an al
lowlist is a list of origins that takes one or more of the fol
lowing values, separated by spaces: *: the feature will be al
lowed in this document, and all nested browsing contexts (iframes) regardless of their origin. 'self': the feature will be al
lowed 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 al
lowed 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 <al
lowlist>; <al
lowlist> an al
lowlist is a list of origins that takes one or more of the fol
lowing values, separated by spaces: *: the feature will be al
lowed in this document, and all nested browsing contexts (iframes) regardless of their origin. 'self': the feature will be al
lowed 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 al
lowed to gather information about the orientation of the device through the magnetometer interface. syntax feature-policy: magnetometer <al
lowlist>; <al
lowlist> an al
lowlist is a list of origins that takes one or more of the fol
lowing values, separated by spaces: *: the feature will be al
lowed in this document, and all nested browsing contexts (iframes) regardless of their origin. 'self': the feature will be al
lowed 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 al
lowed to use audio input devices. when this policy is enabled, the promise returned by mediadevices.getusermedia() will reject with a notal
lowederror. syntax feature-policy: microphone <al
lowlist>; <al
lowlist> an al
lowlist is a list of origins that takes one or more of the fol
lowing values, separated by spaces: *: the feature will be al
lowed in this document, and all nested browsing contexts (iframes) regardless of their origin. 'self': the feature will be al
lowed 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 al
lowed 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 <al
lowlist>; <al
lowlist> an al
lowlist is a list of origins that takes one or more of the fol
lowing values, separated by spaces: *: the feature will be al
lowed in this document, and all nested browsing contexts (iframes) regardless of their origin. 'self': the feature will be al
lowed 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
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 al
low or access-control-al
low-methods (for cors) response headers. ...
...And 2 more matches
A typical HTTP session - HTTP
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 al
low 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, fol
lowed by line feed), divided into three blocks: the first line contains a request method fol
lowed 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, al
lowing 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
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 al
lows 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 f
low 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 be
low 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 fol
lowing 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 al
low 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 fol
lowing 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 al
lows 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 fol
lowing 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 fol
lowing 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.tolocale
lowercase is deprecated; use string.prototype.tolocale
lowercase instead warning: string.tolocaleuppercase is deprecated; use string.prototype.tolocaleuppercase instead warning: string.to
lowercase is deprecated; use string.prototype.to
lowercase 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 al
lows 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 al
lows 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 fol
lowing 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 fol
lowing 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 be
low 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 al
lows 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 fol
lowing 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 fol
lowing unicode extension keys are al
lowed: 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 be
low). kn whether numeric collation should be ...
... "standard" and "search" values are ignored; they are replaced by the options property usage (see be
low). 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 fol
lowing 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 fol
lowing unicode extension keys are al
lowed: 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 fol
lowing 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 be
low. ...
...be represented in a locale object by numberingsystem are standardized by unicode. a table of the standard unicode numeral systems can be seen be
low. ...
...n a locale object by numberingsystem are standardized by unicode. a table of the standard unicode numeral systems can be seen be
low. ...
...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 al
lows 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, fol
lowed by one or one- to eight-letter or digit tags. this extension al
lows 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 fol
lows 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. fol
lowing, 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 al
lows 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 be
low 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 be
low) 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 be
low) 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 fol
lowing 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 be
low. ...
...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 be
low. 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" be
low. 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.tolocale
lowercase( [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 to
lowercase(). 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, yel
low, green] = foo; console.log(red); // "one" console.log(yel
low); // "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 al
lows 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 be
low. 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 be
low), 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 be
low, 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 be
low, 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 fol
lowing 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 al
lows 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 al
lows 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 al
lowed. 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. be
low 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 al
lowed. 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 fol
lowing 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 be
low 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 s
lower 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 s
low 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 s
lower 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. s
low 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 fol
lowing 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 "ref
low". 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 al
low 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 al
low 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 overf
low 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 al
lows 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 al
lows 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
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 fol
lowing : <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 fol
lowing: <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 fol
lowed 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
<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 fol
lowing 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 be
low 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 fol
lowing 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 al
lows 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 fol
lowing 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 be
low). 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 al
lows 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 al
lowing you to provide a cryptographic hash that a fetched resource must match. http access-control-al
low-origin the access-control-al
low-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
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 al
lows 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 fol
lows. 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 al
lows 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 fol
lowing 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 fol
lowing 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, al
lowing 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 al
lows 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 al
lows 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 al
lows 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 al
lows 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 fol
lowing: 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 al
low 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. al
low permissions for the content, with the fol
lowing 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 fol
low 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 s
low, 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, fol
lowed 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 fol
lows. 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, al
lowing 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 s
low-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 fol
lowing 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 fol
lowing: 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 fol
lowing: 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 fol
lowing: 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 fol
lowing: 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 al
low 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 fol
low 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 be
low, the native handle to the most recent navigator:browser is obtained and then it is focused. run the snippets be
low 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 fol
lowing: var preferences = preferences.queryinterface(components.interfaces.nsiprefbranch2); this al
lows 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 fol
lowing: var preferences = preferences.queryinterface(components.interfaces.nsiprefbranch2); this al
lows 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 fol
lowing: // |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 fol
lowing 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 al
low 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 fol
lowing 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 al
lows 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").to
lowercase(), 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 be
low 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 al
low 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 fol
lowed as appropriate. xpcom contract ids, for instance, should always begin with an @, fol
lowed 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 fol
low 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 al
lowed 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 stackoverf
low: 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 al
low 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 fol
lowing 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, al
lowing 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 fol
lowing 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 fol
lowing 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 fol
lowing: 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 fol
lowing: 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 fol
lowing 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 al
low 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 al
lows 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 al
lows 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 al
lows you to choose which attributes you want it to observe. broadcasters al
low 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 al
low 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 al
low 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 fol
lowing 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 al
lows 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 fol
low. 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 fol
lowed 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 fol
low 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 s
low 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 s
lowed 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 s
low dom mutations. the technique was adapted from the method used by the x-tag library. the code be
low 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 fol
lowing: 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 fol
lowing 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 al
low 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 fol
lowing 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 fol
lowing 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 fol
lowing: 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 fol
lowing: 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 al
lows 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 fol
lowing 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, al
lows 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 be
low. 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 be
low. while the technical details be
low 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 fol
lowing file, for instance, would change the default keyword search engine, assuming that an engine with the name example engine is installed, as described be
low: // 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 fol
lowing 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 fol
lows: 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 al
lowing 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> fol
lowed 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 be
low. 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 fol
lowing 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 al
lows 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 al
lows 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, al
lowing 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 al
lows 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. fol
lowing on from the above example, to create a new window, we would do the fol
lowing: // 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 ref
lows 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 al
lows 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 al
lows 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 fol
low 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 be
low. 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 fol
lowing code works with spidermonkey's hacked version of nanojit. figuring out how to compile it is left as an exercise for the reader; the fol
lowing 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 fol
lowing 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 overf
low 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 overf
low. 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 al
lows 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 al
low 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 al
low 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, al
lowing 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 fol
lowing section. methods of the window.platform object can be called from webapp.js or from web content. the fol
lowing 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 fol
lowing frames can be found by using the getnextinf
low() 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 fol
lowing frames can be found by using the getnextinf
low() method of nsiframe. the initial ref
low is done by the nshtmlcontentsink::startlayout(), startlayout() calls presshell::initialref
low(). startlayout is called quite early in the parsing process, for html it's called in nshtmlcontentsink::openbody() (among other places). todo: how are nsiframes ref
lowed 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 fol
lowing 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 be
low. 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 be
low. 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 fol
lowing 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 fol
lowing 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 fol
lows: err = file.execute(myfile, '"-c""-d""-s"', true); //technically, given the rules above, you could also pass the same //arguments with the fol
lowing 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 al
lows 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 fol
lowing 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 be
low. 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 fol
lowing 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 al
lows 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 fol
lowing 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 fol
lowing 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 be
low 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 fol
lowing 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 (gdisal
lowed) event.preventdefault();"> <menuitem label="undo"/> <menuitem label="redo"/> </menupopup> </menu> in this example, a global variable gdisal
lowed 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 fol
lowing 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 be
low 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 fol
lowing 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 be
low is copied for each result. for example, if the example were modified to the fol
lowing: <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 fol
low 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 al
low sorting by a certain column, you can leave out the sort attribute. only specify this attribute on columns that you wish to al
low 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 fol
lowing: sort="?name ?gender" in this example, results will be sorted by name, fol
lowed 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 fol
lowing examples, we are going to use the fol
lowing 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 fol
lowed 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 fol
lowing 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 fol
lowing 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 al
lowed 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 fol
lowing: <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 al
lows 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 fol
lowing 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 be
low 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 be
low: #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 be
low: <?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 be
low, al
lowing 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 fol
lowing 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 s
lowly. 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 fol
lowing 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 be
low. 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 fol
lowing 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 fol
lows: 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 fol
lowing 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 al
low 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 fol
lows: 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 fol
lowing 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 al
lows 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 be
low 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 fol
lows: <treeitem container="true" /> this al
lows 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 be
low. 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 be
low 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 be
low 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 be
low 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 al
lows 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 fol
lows: <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 fol
lowing 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 al
low 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.al
low_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.al
low_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 "al
lowxulxbl", like this: components.classes["@mozilla.org/permissionmanager;1"] .getservice(components.interfaces.nsipermissionmanager) .add(uri, 'al
lowxulxbl', components.interfaces.nsipermissionmanager.al
low_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 s
low 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 fol
lowing 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 al
low 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 fol
lowing 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 fol
lowing 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 s
lower 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 fol
lowed 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 fol
lowed 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, , al
lowevents, , 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="yel
low"/> <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, al
lowevents, al
lownegativeassertions, 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 al
lowed 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 fol
lowing 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 al
lowed 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 al
lows 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 al
lowed 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
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 be
low 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 fol
lowing 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 al
lowed 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 be
low 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 fol
lowing 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 al
lowed 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 al
lowed 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 al
lowed 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 al
lows 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 be
low 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 fol
lowing 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, , al
lowevents, , 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 be
low 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 al
lowed 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 be
low used to indicate whether multiple selection is al
lowed. 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 fol
lowing 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 al
lows 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
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 al
lows 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, , al
lowevents, , 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
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 be
low 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 fol
lowing 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 al
lowed 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 be
low 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 fol
lowing 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 fol
lowing 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 al
lows 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 be
low 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 al
lows 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 be
low 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 al
lows 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
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 be
low 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, , al
lowevents, , 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 fol
low 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 fol
lows. 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 fol
lows: ; 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 fol
lowing 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 fol
lowing: 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 fol
lows: 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 fol
lows: 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 fol
lowing 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 fol
lowing 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 al
low 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 fol
lowing: 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 al
low 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 be
low. 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 fol
lowing 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 fol
lowing 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 fol
lowing post. discussions sparky and comet going away on friday on october 19th j. paul reed posted the fol
lowing 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 fol
lowing code: var observerservice = components.classes["@mozilla.org/observer-service;1"] .getservice(components.interfaces.nsiobserverservice); observerservice.removeobserver(this, "experimental-notify-plugin-call"); skeleton observer class be
low 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 <b>bold</b>.</description> note that the "<" has been turned into "<". and the ">" has been turned into ">". this greatly bloats the size of contents but is necessary since certain characters are no al
lowed 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 al
lowed. ...
...the rss <description> element and put non-plain text data in it. it is not actually al
lowed. the rss 2.0 specification clearly states that “entity-encoded html is al
lowed“ 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 fol
low the same steps as the tamarin central instructions. http://developer.mozilla.org/en/docs...mpliance_tests running tamarin performance tests fol
low 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 al
low 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 fol
lowing command should generate a suitable key pair: ssh-keygen -t dsa this will take a moment, fol
lowed 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 fol
lowing 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 fol
lowing 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 be
low 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-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 fol
lowed 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 { overf
low-x: auto; overf
low-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-overf
low-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-overf
low-style: none; width: 480px; height: 270px; overf
low: 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 fol
lowed 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 be
low 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 { overf
low-x: auto; overf
low-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-overf
low-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-overf
low-style: none; width: 480px; height: 270px; overf
low: 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 fol
lowing 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 fol
lowing document modes: quirks, internet explorer 6 standards, internet explorer 7 standards, internet explorer 8 standa...
XForms Select Element - Archive of obsolete content
introduction al
lows 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', al
lows 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 al
lows 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 fol
lowing 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 al
low 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 al
low 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 fol
lowing 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 fol
low 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 fol
lows 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. fol
lowing 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 s
lower 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 be
low 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 fol
lows: 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 al
lows us to adjust it by wrapping and filtering it if necessary. texture wrapping al
lows 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 fol
lowing 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 be
low, 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 fol
lowing 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 al
lows 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, al
lowing 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 al
lowed 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-b
lown 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 be
low 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 fol
lows. 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 fol
lowing lines to your code be
low 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 fol
lowing just be
low 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 fol
lowing line inside draw(), just be
low 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 fol
lowing 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 be
low 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 fol
lows: 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 be
low: 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 be
low: 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 fol
lowing 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 fol
lowing 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 be
low, 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 fol
lowing 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 fol
lowing 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 fol
lowing 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. ...
...e
low 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 fol
lowing 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 be
low. * {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 fol
lows: "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 fol
lows: "select count(*) from users where username=' admin ' and password=' passwd123 ' "; if the credentials are correct, then the user is al
lowed 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 al
lowed 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 fol
lows: "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 fol
lowing: $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 fol
lowing 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 workf
low. ...
...opment workf
low. 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 al
low 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 al
low 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 fol
lowing 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 fol
lowed by a hyphen. in the example be
low 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 al
low 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 be
low, 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 be
low, 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 be
low, 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 be
low, 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 be
low. try updating the live code be
low 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 be
low 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 be
low 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 be
low 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 be
low 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 be
low, 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 overf
low 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 overf
low 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 overf
low if there is too much. try updating the live code be
low 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 be
low 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 be
low 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 be
low 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 be
low, 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 be
low. try updating the live code be
low 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 be
low 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 be
low 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 be
low 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 be
low. try updating the live code be
low 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 be
low. try updating the live code be
low 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 fol
lowing top, left, bottom and right. you can see how this should look in the image be
low. try updating the live code be
low 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 be
low, 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 be
low. 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 f
low of your page makes sense. a user with a very limited feature phone might not get much of your css, but the content will f
low 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 be
low 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 al
low 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 f
low elements on webpages lay themselves out according to normal f
low - until we do something to change that. this article explains the basics of normal f
low 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 al
lows you to take elements out of the normal document layout f
low, 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 al
lows 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 al
low 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:// fol
lowed 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 fol
low 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 fol
lowing 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 fol
lowed 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 al
low 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 al
lows 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 fol
lowing 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 s
low 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 s
low 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; overf
low : 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%; overf
low : hidden; white-space : nowrap; text-overf
low : 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 */ overf
low-y: auto; overf
low-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; overf
low : 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 be
low 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 be
low 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. al
low the user to pick multiple files at once. al
low the file picker to accept jpg and png images only. try updating the live code be
low 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 be
low, 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 be
low 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 al
low 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 be
low 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 al
lowing 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 be
low, 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 be
low 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 fol
lowing 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 al
lowing 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 fol
low 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, fol
lowed 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 hol
low 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 fol
lowing 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 fol
lowing 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 al
lowing 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 fol
lowing 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 be
low. 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 fol
lowing 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 be
low 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 be
low 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 workf
low 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 be
low 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 be
low 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 fol
lowing 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 be
low 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 be
low 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 be
low 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 fol
lowing 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 be
low 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 be
low 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 be
low 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 be
low 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 al
lowing 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 al
low you to store data related to web sites and retrieve it when necessary al
lowing 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 fol
lowing: 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 fol
lowing 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 fol
lowing 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 fol
lows: 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 fol
lowing 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 be
low, 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 be
low, 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 be
low 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 be
low 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 be
low 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 be
low, 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 be
low, 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 be
low 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 be
low, 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 be
low, 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 be
low 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 be
low 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 be
low 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 fol
low 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 ref
low (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, al
lowing 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 al
lows an author to indicate that an element and its contents are, as much as possible, independent of the rest of the document tree. this al
lows 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 s
low 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 s
low to display and s
low 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 s
low 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 s
low 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 s
low sites at 3 seconds. the speed at which a site loads is one factor. if the site is s
low 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. s
low 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 fol
lowing guides. the fol
lowing 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 workf
low. ...
...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 workf
low. 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 al
lows 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 al
lows 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 f
low. ...
... 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 fol
lowing code to your app component object, be
low 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(), be
low 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 fol
lows: <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 al
lows you to have direct access to the underlying dom nodes be
low 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 be
low, 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 fol
lows: <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 f
low 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 fol
lows: // 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 fol
lowing 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 fol
lows: 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 al
lows 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 al
lows 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 al
low 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 al
lows 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 fol
lows: 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 al
lows 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 al
lows 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 fol
lowing 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::isal
lowedtodispatchdomevent(). 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 al
lows 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 fol
lowing: 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 fol
lowing 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 al
low 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 al
low $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 al
low 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 s
lower 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 fol
lowing 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 fol
lowing 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 s
low box may take several hours. tips for making builds faster. the executable will be at the location listed under running be
low. 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 be
low) 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 be
low. 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 f
low 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 fol
lowing 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 fol
lowing 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 be
low 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 fol
lowing format for your commit message: `bug number - what your patch does; r?reviewer` for example, a commit message may look like `bug 1234567 - remove ref
low 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: fol
low 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 fol
lowing: 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 fol
lowing 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 be
low) 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 fol
lowing 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 al
low or deny the request. since the code calls to the parent process to check whether a specific request can be al
lowed it would s
low 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 fol
lowing 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, be
low), 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, be
low), 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, be
low) 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 fol
lows: 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 be
low. 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 al
lows 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, al
lowing 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 al
lowdrop() 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, fol
lowing 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 (be
low) in the bug report. if you suspect a hang (as opposed to s
low performance), wait one minute on an idle system before getting the stack trace. the crash report link for a hang, obtained by fol
lowing the steps be
low. 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 fol
lowing 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 "fol
lowing 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 al
lows 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 al
lows 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 al
lowed 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 al
lows 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 fol
lowing 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. eoverf
low (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_nofol
low do not fol
low 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 al
low 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 be
low. 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() al
lows 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 fol
lows: 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 fol
lowing: 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 workf
low. 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 fol
lowing 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 al
lows 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 be
low. 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 fol
lowed 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 fol
lowing command: $ ssh hg.mozilla.org if ssh is working fine, you should see the fol
lowing message: no interactive shells al
lowed 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 fol
low 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 al
lows 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 fol
lowing 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 fol
lowing 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 fol
lowed 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 fol
lowing 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 al
lows {} 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 f
low 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 fol
low 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) al
lows for sharing of style data, which al
lows the data to take up less memory and al
lows the data computation to take less time. ...
...tree) al
lows for sharing of style data, which al
lows the data to take up less memory and al
lows 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 fol
lowing 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 fol
lowing screenshot shows a customized "energy" tab. the power-related columns are as fol
lows. energy impact / avg energy impact: see the separate section be
low. % 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 fol
lowing 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 fol
lowing 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 fol
lows. 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 fol
lowing. 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 be
low), 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 al
lows an xpcom object to be exposed to javascript, and it al
lows 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 s
low, 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 fol
lows: _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 yel
low 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 al
low 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 s
lowing 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 s
lows down firefox while recording the profile. for example you might have one addon that s
lows down page load and another one that s
lows down tab switch. your first reflex once you find what addon is s
lowing 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 al
lows 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 fol
lowing 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 fol
lowing 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 fol
lowing. 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 fol
lowing 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 fol
lowing: 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 al
low 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_overf
low_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 al
lowed 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 al
lowed. 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 al
lows 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 fol
lowing enumerators: pr_ipaddrnull do not overwrite the ip address. this al
lows 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 be
low. 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 fol
lowing 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 fol
lowing 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 be
low. 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 fol
lowing 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 - al
low 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 al
lowed 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 be
low. 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 be
low, 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 be
low, 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 be
low. 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 fol
lowing ca certificate had the websites and code signing trust bits restored to their original state to al
low 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 fol
lowing 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 fol
lowing 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 overf
low. 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 al
low 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 be
low. deprecate the fol
lowing 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_al
low_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_al
low_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_al
low_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 fol
lowing 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 fol
lowing 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 disal
lows 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 fol
lowing 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 fol
lowing 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 be
low). 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 fol
lowing 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 al
lowed 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 fol
low 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 fol
lowing 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 fol
lowing 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 be
low 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 al
lows 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 fol
low 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 fol
lowing 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 fol
lowing certfile is raw binary der (default) -t fol
lowing 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 fol
lowing 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 fol
lows. 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 fol
lows. possible flags: "testlocalinfofirst" and "requirefreshinfo". -m method type sets method type for the test type it fol
lows. possible types are "crl" and "ocsp". -s method flags sets revocation flags for the method it fol
lows. 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 al
low 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 fol
lowing: 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 al
low 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 fol
lowing: 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
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 be
low 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 al
lows 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 fol
low 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 fol
lowing certfile is raw binary der (default) -t fol
lowing 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 fol
lowing 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 fol
lows. 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 fol
lows. possible flags: "testlocalinfofirst" and "requirefreshinfo". -m method type sets method type for the test type it fol
lows. possible types are "crl" and "ocsp". -s method flags sets revocation flags for the method it fol
lows. 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 fol
lowing 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 al
lows 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 al
low 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 fol
lowing 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 fol
low 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 be
low. 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 (be
low); 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 fol
low 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 fol
lowing 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 al
low 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 fol
lowed 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 be
low. 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 al
low 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 be
low) representing the parsed abstract syntax tree (ast). additional options may be provided via the options object, which can include any of the fol
lowing 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 fol
lowing 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 be
low 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 fol
lowing 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 be
low 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 b
lowing 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 s
low. 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 s
low. 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 al
lowed 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 al
lowing 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 al
low 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 al
low 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 fol
lowing 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 fol
lowing: 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 fol
lowing 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 al
lows 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 al
lows 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 al
lows 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 fol
lowing 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 fol
low 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 al
lowing 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 be
low 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 al
lowed 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 fol
lowing 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 al
lowing 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 al
lows 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 fol
lowing contents: for (prop in arguments) { print(prop + "=" + arguments[prop]); } entering the fol
lowing at the command line should produce the fol
lowing 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 fol
lowing 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() al
lows 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 al
low any other language to use the xpcom api, a bridging layer is required. the fol
lowing 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 al
lows 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 be
low.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 fol
lows: 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 fol
lows: 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 fol
lows: 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 fol
lows: 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) al
low 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 fol
lowing 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', 'stackoverf
low - new messages', 'there are ## new messages. click here to focus the tab', true, null, notiflistener, 'stackoverf
low 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. markpageasfol
lowedlink() 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.markpageasfol
lowedlink() 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 fol
lowed by the user (for example by clicking on it). void markpageasfol
lowedlink( in nsiuri auri ); parameters auri the url that is to be marked as explicitly fol
lowed 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 f
low 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 f
low, 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 f
low. 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 f
low. 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 f
low stops. this method may be used during any stage of event f
low. 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 fol
lowing 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 al
lowed. 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 al
lowed. 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 al
lowed 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 aal
lowdelayedload, [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 aal
lowdelayedload 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 aal
lowdelayedload 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"); aal
lowdelayedload 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 aal
lowdelayedload flag, meaning that the loader will no longer load the script into new frames. if you used aal
lowdelayedload, 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 al
lowport() 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.al
lowport(). boolean al
lowport( 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 al
lowed, 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) fol
lowed 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. fol
lowlinks 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 fol
lowlinks 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 fol
lowing 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 be
low. 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 fol
lowlinks attribute. if the file object is an alias and fol
lowlinks is true, returns the target of the alias. if fol
lowlinks 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 fol
lowlinks is true, returns the target of the alias. if fol
lowlinks 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 fol
lowlinks attribute. if the file object is an alias and fol
lowlinks is true, returns the target of the alias. if fol
lowlinks 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 fol
lowlinks 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 al
low 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 be
low. read only. path autf8string the path that this memory usage should be reported under. paths are delimited with '/' characters to al
low 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 fol
lowing 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 al
lows 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 al
low 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 fol
low 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 al
low 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 al
low 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 al
lowing 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 fol
lowing 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 be
low. 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 fol
lowing flags control the f
low 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 fol
lowing 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 fol
lowing 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 al
low 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 al
lowadjacent, 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. al
lowadjacent specifies whether the returned ranges are al
lowed 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 al
lowadjacent, in rangearray results ); parameters beginnode beginoffset endnode endoffset these four parameters represent the range to compare against the selection. al
lowadjacent specifies whether the returned ranges are al
lowed 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 al
lows 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 al
lowed 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 "b
low", you can play the mac os x "b
low" 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 al
lows 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 al
lowed 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 fol
lowing 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 be
low 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 b
low 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 fol
lowing 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 fol
lowing 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 fol
lowing 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() al
lows 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 fol
lowing 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 al
lows 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 fol
lowing 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 al
lows 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 al
lows 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 al
low 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 fol
lowing 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 al
lows 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 al
lows 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, al
lowing 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: al
lowremotecontent 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 fol
lowed, 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 fol
lowing 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 al
lows us to set an http request header. be
low 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 be
low. 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 fol
lows: 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 fol
lowing. 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 al
low 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 be
low 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 be
low. 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 al
lows 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 be
low, 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 al
lows 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 fol
low 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 fol
low 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 fol
lowed 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 fol
lowing 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 fol
lowing: // // 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 al
lows 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 fol
lows: #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 al
lows 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 fol
low 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 al
lows 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 al
lows 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 al
lows 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 fol
lows the fol
lowing 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 be
low. 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 be
low. 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 fol
lowing 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 be
low. 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 fol
lowing preferences: // this al
lows 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 be
low, 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('al
lowtabmodal', 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 be
low, 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 fol
lowing 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 fol
lowing 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, s
lowing 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. fol
low 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 fol
low 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. fol
low 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 fol
lows: windows: hdc mac os: pointer to np_port structure. unix/x11: not used. (the drawable is provided in the paint message. see be
low.) 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 be
low 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 al
lows 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 be
low 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 fol
lowing 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 al
lowed 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 al
lowed 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 al
lowed 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 fol
lowing 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 fol
lowing 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 al
lows 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 al
lows 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 al
lows 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 al
lows 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 overf
low: scroll or overf
low: auto applied to it, and it has scrollable overf
low. 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 fol
lowing 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 fol
lowing format: screen shot yyy-mm-dd at hh.mm.ss.png the command has the fol
lowing 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) fol
lowed 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, fol
lowed 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), fol
lowed 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 fol
lowed 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 fol
lowing: 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 fol
lowing 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 al
lows 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 fol
lowing parent interfaces: <div id="interfacediagram" style="display: inline-block; position: relative; width: 100%; padding-bottom: 11.666666666666666%; vertical-align: middle; overf
low: 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 fol
lowing 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 fol
lowing 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 al
lows 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 al
low 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 al
lowed 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 al
lows 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 al
low 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 be
low) 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 f
low. ...
...mentrequest(supportedinstruments, details, options); // add event listeners here. // call show() to trigger the browser's payment f
low. 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 f
low 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 fol
lowing 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 be
low) 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 f
low. ...
...mentrequest(supportedinstruments, details, options); // add event listeners here. // call show() to trigger the browser's payment f
low. 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 f
low 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 be
low). 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 be
low). 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 fol
low the spec for the dialog box. an almost-cross-browser working example would be close to the be
low 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 be
low. 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" be
low) 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 fol
lowing 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 — al
lows developers to explicitly define their css custom properties, al
lowing 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 fol
lowing uses css.registerproperty in javascript to type a css custom properties, --my-color, as a color, give it a default value, and not al
low 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 fol
lowing @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 fol
lowing 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 fol
lowing 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 be
low, 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; } be
low 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 fol
lowing 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; overf
low: 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
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 fol
lowing output by another level. to move back out a level, call groupend(). console.groupcollapsed() creates a new inline group, indenting all fol
lowing 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 fol
lowed 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: yel
low; 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 fol
lows (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 be
low, 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 effectal
lowed 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 + " ; effectal
lowed = " + ev.datatransfer.effectal
lowed); // 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.effectal
lowed = "move"; } function drop_handler(ev) { console.log("drop: dropeffect = " + ev.datatransfer.dropeffect + " ; effectal
lowed = " + ev.datatransfer.effectal
lowed)...
...tatransfer.dropeffect + " ; effectal
lowed = " + ev.datatransfer.effectal
lowed); 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 + " ; effectal
lowed = " + ev.datatransfer.effectal
lowed); 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 be
low!</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 fol
lowing 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 be
low, 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 be
low. 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 = al
lowvideoflag; displaymediastreamconstraints.video = mediatrackconstraints; displaymediastreamconstraints = { video: al
lowvideoflag | 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 fol
lowing strings, or an array of them to al
low 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 fol
lowing strings, or a list of them to al
low 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 al
low the user to choose source surfaces which do not directly correspond to display areas. these may include backing buffers for windows to al
low 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 fol
lowing 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 al
low 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 fol
lowing 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 fol
lowing 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 + " <p>...
...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
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 fol
lowing 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() al
lows 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 fol
lowing 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
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 be
low 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". be
low 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 be
low 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 be
low! fol
low the white rabbit example in the fol
low 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 fol
lowing 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 overf
lowing children, these checks determine if the container can scroll: window.getcomputedstyle(element).overf
lowy === 'visible' window.getcomputedstyle(element).overf
lowy !== '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
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 f
low, 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
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 al
low 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 fol
lowing 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 al
low 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, al
lowing 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, al
lowing 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, al
lowing 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 fol
lowing: 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 al
lowed. 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_al
lowed_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 fol
lowing 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
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 al
lows 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 al
lows access to the items in this list. for example, if the html includes the fol
lowing file input: <input id="fileitem" type="file"> the fol
lowing 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 be
low!</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 fol
lowing 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 be
low, 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 be
low. 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, al
lowing 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 al
lows 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 fol
lowing attributes have been added: autofocus, formaction, formenctype, formmethod, formnovalidate, formtarget, labels, validity, validationmessage, and willvalidate. the fol
lowing 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.al
low is a list of origins the the frame is al
lowed 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.al
lowfullscreen 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 fol
lowing property has been added: al
lowfullscreen. html5the definition of 'htmliframeelement' in that specification. recommendation the fol
lowing properties are now obsolete: scrolling, marginwidth, marginheight, longdesc, frameborder, and align. the fol
lowing 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 fol
lowing 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, al
lowing the fol
lowing text to f
low 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 fol
lows will f
low against the image's right edge. right floats the image to place its right edge flush against the right margin. subsequent text will f
low 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 fol
lowing, conceptually: <select> <option value="1">option: value 1</option> <option value="2">option: value 2</option> </select> */ the before parameter is optional. so the fol
lowing 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 fol
lows 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 fol
lows 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 { overf
low: 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 fol
lowing attributes have been added: autofocus, placeholder, dirname, wrap, maxlength, required, textlength, labels, selectionstart, selectionend, selectiondirection, validity, validationmessage, and willvalidate. the fol
lowing 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 fol
lows (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 fol
lows (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
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. ...
... al
lowing 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 al
lowing 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 al
lowing 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 fol
lowing 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 al
lows 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 al
lows a wider variety of objects to be safely passed. example of replacestate() method suppose http://mozilla.org/foo.html executes the fol
lowing 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 al
lowed 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 fol
lowing code: timeout_err if reserving all the database objects identified in storenames takes longer than the timeout interval. ...
IDBKeyRange.bound() - Web APIs
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 fol
lowing type: exception description dataerror the fol
lowing 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 al
lows data to be read but not changed. readwrite al
lows reading and writing of data in existing data stores to be changed. versionchange al
lows 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 fol
lows 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 al
lows access to a set of data in an indexeddb database, looked up via primary key. idbindex also al
lows 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 fol
lowing 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 fol
lowing, 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 fol
lowing 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() al
lows to retrieve the file metadata (size and date of the last modification). returns a filerequest. lockedfile.readasarraybuffer() al
lows 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() al
lows to retrieve the file metadata (size and date of the last modification). returns a filerequest. lockedfile.readasarraybuffer() al
lows to retrieve a part of the content of the file as an arraybuffer. returns a filerequest object. lockedfile.readastext() al
lows to retrieve a part of the content of the file as a string. returns a filerequest object. lockedfile.write() al
lows to write some data in the file starting at the location offset. returns a filerequest object. lockedfile.append() al
lows to write some data at the end of the file. returns a filerequest object. lockedfile.truncate() al
lows 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 be
low 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 al
lows 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 al
lows 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 al
lows the capabilities to be configured within the constraints what the device al
lows. mediastream image capture concepts and usage the process of retrieving an image or video stream happens as described be
low. 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 be
low 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 al
low 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 f
low 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 fol
lowing 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 al
low 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 al
lows 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 al
lowed to use a particular payment handler (e.g., registered as al
lowed 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 fol
lowing 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 fol
lowing performanceentry properties (for "paint" performance entry types) by qualifying and constraining the properties as fol
lows: 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 al
low 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 fol
lowing 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 al
low 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 be
low, 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 fol
lowing 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 f
low. 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 fol
lows: no active touches is white; one active touch is yel
low; 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 // yel
low - one pointer down // pink - two ...
...lement has no touch points i.e. no pointers down // yel
low - 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 = "yel
low"; 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 f
low). // 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 fol
lowing 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 be
low, 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 fol
lowing 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
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_al
lowed_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_al
lowed_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
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_al
lowed_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_al
lowed_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_al
lowed_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_al
lowed_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
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 fol
lows: 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 al
lowed multiple ranges (for instance, to al
low 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 fol
lows: 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 fol
lowing methods: selection.collapse() selection.collapsetostart() selection.collapsetoend() selection.extend() selection.selectallchildren() selection.addrange() selection.setbaseandextent() and when the range is modified using the fol
lowing 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 stackoverf
low). 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 fol
lows: 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, fol
lowed by a colon, fol
lowed by the text data for that field's value. fields each message received has some combination of the fol
lowing 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 f
low. update background color the background color of the touch areas will change as fol
lows: no touch is white; one touch is yel
low; 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...
... fol
lows: no touch is white; one touch is yel
low; 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: // yel
low - one tap (or hold) // pink - two taps // lightblue - more than two taps switch (ev.targettouches.length) { case 1: // single tap` ev.target.style.background = "yel
low"; 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 f
low. 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 fol
lowing 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 fol
lowing 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 fol
lowing 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
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 '#' fol
lowed by the fragment identifier of the url. host a usvstring containing the domain (that is the hostname) fol
lowed 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 '/' fol
lowed 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, fol
lowed 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 fol
lowing 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 al
lowing iteration through all key/value pairs contained in this object. urlsearchparams.foreach() al
lows 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 al
lowing 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 al
lowing 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 be
low distortion curve code on stack overf
low. 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 be
low distortion curve code on stack overf
low. 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 fol
lowing 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 al
lowing the red component of pixels to be updated, and therefore it is as if you were looking through a red tinted glass. color masking al
lows 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 al
lows 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 fol
lowing 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 fol
lowing 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 be
low. 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 f
low 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 fol
lowing 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 al
low 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 al
lows 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 al
low 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 al
low you to directly connect with peers. ice uses stun and/or turn servers to accomplish this, as described be
low. 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, fol
lowed by an equals sign ("="), fol
lowed 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 be
low. 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 be
low. 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 be
low. 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 be
low, 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 bufferedamount
low the amount of data currently buffered by the data channel—as indicated by its bufferedamount property—has decreased to be at or be
low the channel's minimum buffered data size, as specified by bufferedamount
lowthreshold. 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 fol
lowing 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() fol
lowed 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 fol
low, which provides transparency in negotiation while al
lowing 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 al
low 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 be
low. 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 al
low 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 yel
low-tinted glasses, you can add a yel
low 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, fol
lowed 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 al
lowed if all of the fol
lowing 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 be
low 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 al
low 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 fol
lowing 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 be
low. 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", "yel
low", "green" ], // offset: 0, 0.5, 1 }, 2000); the special keys offset, easing, and composite (described be
low) 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 be
low. the fol
lowing 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 al
lows 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 al
lows 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 fol
lows: 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 f
low 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, al
lowing 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 al
low 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, al
lowing 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
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 al
low-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 al
low-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 al
low-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 al
low-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 al
low-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 al
low-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 al
low-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 s
low 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 al
lowed 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 fol
lowing 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 fol
lowing 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 al
low 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 al
low 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 fol
lowing: 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. fol
lowing 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 be
low 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 fol
lowing 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 fol
lowing 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 al
lows 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 be
low. 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 fol
lowing 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 fol
lowing, 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 fol
lowing needs to be done: the dialog must be properly labeled keyboard focus must be managed correctly the sections be
low 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 al
lows 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 fol
lowing: 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, fol
lowed 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 fol
lowing 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 fol
lowing 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 be
low 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 fol
lowing 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 fol
lowing: 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 be
low 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 be
low 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 be
low 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 be
low 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 be
low 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 be
low 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 al
lows 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 al
lowed 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 al
lows 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 al
lows 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 fol
lowing 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 al
low 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 al
low 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 fol
lowing 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 be
low 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 be
low 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 be
low), but at least meet the aa rating (see 1.4.3 be
low). if you are including non-text content such as video or animation, you should fol
low 1.4.11 (again, see be
low). 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 fol
lows, 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
ation decided by the cascading algorithm. ...
...okens, so long as the sequence does not contain an unal
lowed 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 fol
lows 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 be
low.) 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 al
lowed 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 al
lows 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 al
lows 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 fol
lowing 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 al
lows 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 al
lows 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 al
lows 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 al
lows 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 al
lows 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 al
lows 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 al
lows 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 al
lows 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 al
lows 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 al
lowing 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 be
low. <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 overf
low. 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 al
low 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 overf
low. 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 fol
lows. 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 f
low-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 f
low-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 fol
lowing 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 f
low-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 f
low 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 f
low 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 be
low 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 be
low 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 fol
low 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 be
low 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 al
lows resizing in the inline dimension and resize: block al
low 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 be
low 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 be
low, 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 be
low you can see how the margin, border, and padding on the inline <span> element are added. note: i am using the logical, f
low-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 be
low 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 be
low 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 al
lowed. <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 al
lowed. ...
... 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 fol
lows: 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 al
lows 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 al
lows 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. fol
lowed 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
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 overf
low. if a value of multiple is specified, however, then the box is al
lowed 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 overf
low out of the box. the later lines are placed be
low 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 be
low. ...
...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 al
lowing 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 be
low 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 al
lowed. 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 fol
lows: …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 fol
lowing 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 f
low 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 be
low. values generic break values auto al
lows, 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 fol
lows: 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 fol
lowing 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 fol
lowing 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 f
low 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 be
low. values generic break values auto al
lows, 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 fol
lows: 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 fol
lowing 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 fol
lowing 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 f
low 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 be
low. values auto al
lows, 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 be
low. values top the caption box should be positioned above the table. bottom the caption box should be positioned be
low 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 be
low 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 be
low 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 be
low 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
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 be
low. 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 fol
lowing 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 fol
lowing clippath definition: <pre> <svg> <clippath id="mypath" clippathunits="objectboundingbox"> <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" /> </clippath> </svg></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; overf
low: 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
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 fol
lowing: 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 overf
lows 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 fol
lowing are lines (almost) identical: cross-fade( url(red.png), url(yel
low.png), url(blue.png)); /* all three will be 33.3333% opaque */ cross-fade( url(red.png) 33.33%, url(yel
low.png) 33.33%, url(blue.png) 33.33%); older, implemented syntax cross-fade( <image, <image>, <percentage> ) the specification for the cross-fade() function al
lows 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, fol
lowed 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 yel
low/red/blue example (with three images) from the specification synta...
cursor - CSS: Cascading Style Sheets
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-al
lowed. not-al
lowed 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 f
low 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 f
low. inline the element generates one or more inline element boxes that do not generate line breaks before or after themselves. in normal f
low, 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 f
low, 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 fol
lows 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 fol
lows the run-in box, the run-in box becomes the first inline box of the block box. if an inline box fol
lows, 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 fol
lows the run-in box, the run-in box becomes the first inline box of the block box. if an inline box fol
lows, 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 f
low. 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 f
low 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 f
low. 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 f
low layout. examples in the fol
lowing 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 al
lowable range. for example, a color component greater than 255 or smaller than 0 will be clipped to the closest al
lowed 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 al
lows 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 s
lowly, accelerates sharply, and then s
lows 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 s
lowly, 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 s
lowly, 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 s
lowly, speeds up, and then s
lows 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 s
lows down towards the end. this keyword represents the easing function cubic-bezier(0.0, 0.0, 0.58...
float - 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. 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 be
low. 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 f
low 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 be
low 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 be
low, 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 be
low 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 ber
low (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; overf
low: scroll; } .sample { font: 2rem 'amstelvaralpha', sans-serif; } html, body { max-height: 100vh; max-width: 100vw; overf
low: 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
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 fol
lowing 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 fol
low 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 be
low 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, fol
lowed 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 overf
lows 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> | <overf
low-position>? [ <self-position> | left | right ] | legacy | legacy && [ left | right | center ]where <baseline-position> = [ first | last ]? baseline<overf
low-position> = unsafe | safe<self-position> = center | start | end | self-start | self-end | flex-start | flex-end examples simple demonstration in the fol
lowing example we have a simple 2 x 2 grid layout. initially the grid container is given...
<length> - CSS: Cascading Style Sheets
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> fol
lowed by one of the units listed be
low. 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 al
low 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 fol
lowing 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 be
low it once you've pressed return. this al
lows 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 fol
lowing: 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 be
low). <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 be
low). -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
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: yel
low; } .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 be
low. values auto the default scroll overf
low behavior occurs as normal. contain default scroll overf
low 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 yel
low 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; overf
low: auto; position: relative; top: 50px; left: 50px; overscroll-behavior-block: contain; } div > div { height: 1500px; width: 100%; background-color: yel
low; 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 be
low. values auto the default scroll overf
low behavior occurs as normal. contain default scroll overf
low 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 yel
low 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; overf
low: auto; position: relative; top: 50px; left: 50px; overscroll-behavior-inline: contain; } div > div { height: 100%; width: 1500px; background-color: yel
low; 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 al
lows 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 overf
low 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 fol
lowing 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 fol
lowing 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 overf
low-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 fol
lowing 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 overf
low-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 fol
lowing 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 al
lowed by this type. examples use in calc() where a <time-percentage> is specified as an al
lowable type, this means that the percentage resolves to a time and therefore can be used in a calc() expression. ...
...al
lowed by this type. examples use in calc() where a <time-percentage> is specified as an al
lowable 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 al
lowed 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 al
lowed 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 al
lowed 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: yel
low; 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: yel
low; 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: yel
low; 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: yel
low; 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: yel
low; 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: yel
low; 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: yel
low; 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: yel
low; 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 be
low. 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 al
lowed. <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 al
lowed. line-relative values the fol
lowing 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 al
lowed. 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 s
low 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 fol
lowing 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 fol
lowing 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 al
low 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 fol
lowed immediately by children_change::add event_object_hide fol
lowed 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 fol
lowed 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 fol
lowed immediately by text_changed::insert ia2_event_text_removed fol
lowed 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 fol
lowed 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 be
low) 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 fol
lowing 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 al
low 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 be
low 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
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 al
lowed 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 fol
lowing 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 be
low, 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 fol
lowing 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 fol
lowing 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 fol
low all of these, but fol
lowing 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 fol
low these guidelines suggest to the developers of your favorite libraries that they fol
low 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 fol
lowing 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 fol
lowing 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
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 al
lowed 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 al
lowed, the validitystate.rangeoverf
low 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
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 f
low 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 f
low 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 al
lows 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 be
low 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
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 fol
lowing 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 fol
lowing 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
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 f
low 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 be
low. 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 fol
lowing 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 be
low. 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 be
low. 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><dfn></dfn></strong>) is used to indicate the term being defined within the context of a definition phrase or s...
<hgroup> - HTML: Hypertext Markup Language
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 f
low 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 f
low 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 al
lows 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 fol
lowed by parentheses around the secondary heading(s) consider the fol
lowing 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 fol
lowing: that is, the rendered outline might show the primary title, html, fol
lowed by a colon and space, fol
lowed by the secondary title, living standard — last updated 12 august 2016. or, the rendered outline for that document might instead look like the fol
lowing: that is, the rendered outline might show the primary title, html, fol
lowed by the secondary title shown in parentheses: (living...
<input type="button"> - HTML: Hypertext Markup Language
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 be
low 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 be
low 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 al
low 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
<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 be
low the fol
lowing 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 fol
lowing 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 workf
low 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 al
low 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 be
low. 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
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 be
low. 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 al
low one to be selected out of them all, whereas checkboxes al
low 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 al
low 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 be
low. 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 fol
lowing 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
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 f
low 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 fol
lows: <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, al
lowing 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
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 f
low content. tag omission the end tag can be omitted if the list item is immediately fol
lowed 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 al
lowed value for this attribute is a number, even if the list is displayed with roman numerals or letters. list items that fol
low 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
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 f
low 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: f
low 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 f
low 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, f
low 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), f
low 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
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 f
low 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 f
low 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
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 f
low content, palpable content. permitted content phrasing content. tag omission none, both the starting and ending tag are mandatory. permitted parents any element that accepts f
low 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 overf
low 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
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 be
low 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 fol
lowing 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 f
low 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
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, al
lowing 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: yel
low; } </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: yel
low; } </style> </head> <body> <p>this is my paragraph.</p> </body> </html> technical summary content categories metadata content, and if the scoped attribute is present: f
low 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
the html <textarea> element represents a multi-line plain-text editing control, useful when you want to al
low 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 al
low 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 al
low 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 fol
lowing 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 f
low 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
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 f
low 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 fol
lowed 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 fol
lowing 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 be
low 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
<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 be
low 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, al
lows 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 al
lows 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 al
low 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 al
lowed to be used in certain contexts and is disal
lowed 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 f
low 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 fol
lowing: www-authenticate: <type> realm=<realm> proxy-authenticate: <type> realm=<realm> here, <type> is the authentication scheme ("basic" is the most common scheme and introduced be
low). 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 fol
lowed 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 be
low. 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 be
low. 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 fol
lowing mechanisms: x.509v3 certificate extension to al
low 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 al
lowed 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 overf
lows, 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 fol
lowing 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 al
lowed 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 <al
lowlist>; <al
lowlist> an al
lowlist is a list of origins that takes one or more of the fol
lowing values, separated by spaces: *: the feature will be al
lowed 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 <al
lowlist>; <al
lowlist> an al
lowlist is a list of origins that takes one or more of the fol
lowing values, separated by spaces: *: the feature will be al
lowed in this document, and all nested browsing contexts (iframes) regardless of their origin. 'self': the feature will be al
lowed in this document, and in all nested browsing contexts (iframes) in the same origin. 'src': (in an iframe al
low attribute only) the feature will be al
lowed 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 al
lowed in this document, and in all nested browsing contexts (iframes) in the same origin. 'src': (in an iframe al
low attribute only) the feature will be al
lowed 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 al
lowed 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 al
lowed 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 al
lowlist, which is one of: *: the feature is al
lowed by default in top-level browsing contexts and all nested browsing contexts (iframes). 'self': the feature is al
lowed by default in top-level browsing contexts and in nested browsing contexts (iframes) in the same origin. the feature is not al
lowed 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 al
lowed to play a video in a picture-in-picture mode via the corresponding api. syntax feature-policy: picture-in-picture <al
lowlist>; <al
lowlist> an al
lowlist is a list of origins that takes one or more of the fol
lowing values, separated by spaces: *: the feature will be al
lowed in this document, and all nested browsing contexts (iframes) regardless of their origin. 'self': the feature will be al
lowed in this document, and in all nested browsing contexts (iframes) in the same origin. 'src': (in an iframe al
low attribute only) the feature will be al
lowed 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 al
lowed in this document, and in all nested browsing contexts (iframes) in the same origin. 'src': (in an iframe al
low attribute only) the feature will be al
lowed 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 al
lowed 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 al
lowed 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 al
lowlist, which is one of: *: the feature is al
lowed by default in top-level browsing contexts and all nested browsing contexts (iframes). 'self': the feature is al
lowed by default in top-level browsing contexts and in nested browsing contexts (iframes) in the same origin. the feature is not al
lowed in cross-origin documents in nested browsing contexts. 'none': the feature is disabled in top-leve...
...ng contexts (iframes). 'self': the feature is al
lowed by default in top-level browsing contexts and in nested browsing contexts (iframes) in the same origin. the feature is not al
lowed 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 al
low 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 al
lowed to make synchronous xmlhttprequest requests. syntax feature-policy: sync-xhr <al
lowlist>; <al
lowlist> an al
lowlist is a list of origins that takes one or more of the fol
lowing values, separated by spaces: *: the feature will be al
lowed in this document, and all nested browsing contexts (iframes) regardless of their origin. 'self': the feature will be al
lowed in this document, and in all nested browsing contexts (iframes) in the same origin. 'src': (in an iframe al
low attribute only) the feature will be al
lowed 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 al
lowed in this document, and in all nested browsing contexts (iframes) in the same origin. 'src': (in an iframe al
low attribute only) the feature will be al
lowed 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 al
lowed 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 al
lowed 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 al
lowlist, which is one of: *: the feature is al
lowed by default in top-level browsing contexts and all nested browsing contexts (iframes). 'self': the feature is al
lowed by default in top-level browsing contexts and in nested browsing contexts (iframes) in the same origin. the feature is not al
lowed 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 al
lowed to use the webusb api. syntax feature-policy: usb <al
lowlist>; <al
lowlist> an al
lowlist is a list of origins that takes one or more of the fol
lowing values, separated by spaces: *: the feature will be al
lowed in this document, and all nested browsing contexts (iframes) regardless of their origin. 'self': the feature will be al
lowed in this document, and in all nested browsing contexts (iframes) in the same origin. 'src': (in an iframe al
low attribute only) the feature will be al
lowed 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 al
lowed in this document, and in all nested browsing contexts (iframes) in the same origin. 'src': (in an iframe al
low attribute only) the feature will be al
lowed 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 al
lowed 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 al
lowed 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 al
lowlist, which is one of: *: the feature is al
lowed by default in top-level browsing contexts and all nested browsing contexts (iframes). 'self': the feature is al
lowed by default in top-level browsing contexts and in nested browsing contexts (iframes) in the same origin. the feature is not al
lowed 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 al
low 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 fol
lowing 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 be
low 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 al
low 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 al
low 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 al
lows 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 fol
low the one that has already been fol
lowed. 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 fol
lowing 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, be
low. 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 al
low 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 fol
lowing 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 fol
lowing the most recent match. the fol
lowing 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 fol
lowing 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 (\ fol
lowed 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 al
lows 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 overf
low answer by olliej) early versions of javascript did not al
low 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 al
lowing 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 be
low) 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 fol
lowing 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 al
low 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 fol
lowing 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 fol
lowing 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 be
low). 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 fol
lowing 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 fol
lows: 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 be
low.) 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 fol
lowing code at the beginning of your scripts, al
lowing 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 f
lowing 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 fol
lowed 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 fol
lowing 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 fol
lowing 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 fol
lowing 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() al
lows 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 fol
lowing 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 be
low, 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 be
low. '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 fol
lowing 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 al
lows 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 al
lows 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 al
lowlist 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 fol
lows: 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 fol
lowing 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 al
lowing it to be restored even after the browser has been closed, the fol
lowing 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 overf
low/underf
low 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 overf
low/underf
low 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 underf
lows and overf
lows: 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() al
lows 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 al
lows 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 be
low (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 fol
low 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 be
low 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 be
low (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 fol
low 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 be
low 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 overf
low. number.positive_infinity special value representing infinity. returned on overf
low. number.prototype al
lows 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 fol
lowing example shows that a frozen object is not constant (freeze is shal
low). 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 "shal
low 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 al
lowed. 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__ al
lows 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 fol
lowing invariants are violated, the proxy will throw a typeerror: the result must be an object. examples trapping the new operator the fol
lowing 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 be
low. additional properties as explained above, some results contain additional properties as described be
low. 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 fol
lowing example, match() is used to find 'chapter' fol
lowed by 1 or more numeric characters fol
lowed 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 fol
lowing 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 fol
lowing 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 overf
low 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 fol
lowing 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 al
lows 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 fol
low 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 fol
lowing semantics: property value next() a zero-argument function that returns an object with at least the fol
lowing 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 be
low). doing so al
lows 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 fol
lowing operation involving booleans: bcondition1 && bcondition2 is always equal to: !(!bcondition1 || !bcondition2) converting or to and the fol
lowing 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 fol
lowing 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 fol
lowing some rules. the fol
lowing 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 fol
lowing 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 al
lowed 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 al
lows 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. shal
low-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 fol
lowing 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 fol
lowing 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 fol
lowing 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 fol
lowing switch. if break is omitted, the program continues execution at the next statement in the switch statement. examples using switch in the fol
lowing 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 fol
lowing 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 overf
low) multi-case : single operation this method takes advantage of the fact that if there is no break be
low 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 fol
lowing 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 fol
lowing 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 al
low 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 al
lowed. 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 overf
low <math> if an expression is too long to fit in the al
lowed 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 """. scriptlevel <mstyle> controls mostly the font-size. the higher the scriptlevel, the smaller the font size. scriptminsize <mstyle> specifies a minimum font size al
lowed 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 be
low 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
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 be
low scriptminsize in order to avoid unreadable small font sizes and depends on the multiplier specified in scriptsizemultiplier. scriptminsize specifies a minimum font size al
lowed 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 fol
lowing exceptions: height, depth or width do not apply to <mglyph>, <mpadded> or <mtable>. rowalign, columnalign...
<mtable> - MathML
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 al
lows 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 al
lowed 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 al
lowed 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 al
lowed 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 al
lowed 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 al
lows 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 be
low 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, al
low 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 be
low, 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 ref
low/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 f
lows. 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 ref
lows 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 fol
lowing 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 al
low 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 "s
low 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 al
lows 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 al
lowed 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 be
low that, you should be okay. keep in mind, though, that if someone has an older, s
lower 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 al
low 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 al
low 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 fol
lowing 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 al
low 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 fol
lowing 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 fol
lowed by the media type, fol
lowed 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 ...
... fol
lowed 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 (be
low) 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 al
low 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 fol
lows. 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
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 fol
lowing: <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 fol
lowed 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 fol
lowed 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 fol
lowed 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 be
low). 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: yel
low; 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 be
low: 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
svg elements can be modified using attributes that specify details about exactly how the element should be handled or rendered. be
low 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. be
low 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 overf
low 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, overf
low, 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
ink around a text --> <a href="/docs/web/svg/element/text"> <text x="50" y="90" text-anchor="middle"> <circle> </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 be
low */ 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 fol
lowed, 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-f
lowto, 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 fol
lowing screenshot. (firefox users: click here) the rendering process involves the fol
lowing: 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 al
lows 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 al
low 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 fol
lowing 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 overf
low. 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
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 f
lows 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 fol
lowing 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 al
low 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 fol
lowing: 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 al
low 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 fol
lowing 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 al
low 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: al
lows 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: al
lows 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 al
low 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 fol
lows. 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. be
low 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 fol
lows 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 fol
lowing 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 — fol
low 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, fol
lowed by an -o parameter, fol
lowed 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 fol
lowing 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 fol
lowing 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 be
low 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 fol
lowing 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 fol
lowing 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 fol
lowing 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.overf
lowthreshold preference) all of the menu items will instead appear in an overf
low 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 be
low. 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 al
lows 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 al
lows 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 al
lows 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 al
lows 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 fol
lowing command. $ adb shell pm list packages | grep org.mozilla package:org.mozilla.firefox $ jpm-mobile run -b firefox # the package name is firefox -...
...y fol
lowing 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 fol
lowing 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 fol
lowing 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 be
low 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 fol
low 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 fol
lowing 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 fol
lowing 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 fol
low 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 be
low). simple dialog code the fol
lowing 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 fol
lowing 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 be
low 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 al
lows 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 al
low 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 al
low 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 be
low 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 fol
lowing code generate an error as describe in the fol
lowing 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 fol
lowing 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 al
lows 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 be
low). 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 al
lows 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 fol
lowing 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 fol
lowing 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 al
lowed 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 fol
low using a feed reader, such as thunderbird. here are some important feeds you should consider fol
lowing: 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 be
low the tab browser. be
low 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.al
lowimages = false; frame.docshell.al
lowjavascript = false; frame.docshell.al
lowplugins = 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 fol
lowing example are not al
lowed: <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 fol
lowing 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 fol
lowing the steps be
low. 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 fol
lows: 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 al
low (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; al
lows centralized control over layout and appearance for thousands of pages; simple markup al
lows 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 al
lowed 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 al
low 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 al
lows 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 al
low 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 al
lowed 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 fol
low 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 fol
lowing 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 : al
low mismatches in the hostname u : al
low untrusted certs (whether it's self signed cert or a missing or invalid issuer cert) t : al
low 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 fol
lowing command within that directory to accomplish this task: for file in *.jar; do unzip $file; done on operating systems with dos-like shells, the fol
lowing 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 fol
lowing 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 fol
lowing 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 fol
low 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 be
low 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 al
lows 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 al
lows 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 fol
lowing 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
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 fol
lowing 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 fol
lowing 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 fol
lowing 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 al
lows 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 al
lows 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 fol
lowing 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 overf
low arithmetic 116 addxovi integer add int and exit on overf
low 117 subxovi integer subtract int and exit on overf
low 118 mulxovi integer multiply int and exit on overf
low 119 addjovi integer add int and branch on overf
low 120 subjovi integer subtract int and branch on overf
low 121 muljovi integer multiply int and branc...
...c 116 addxovi integer add int and exit on overf
low 117 subxovi integer subtract int and exit on overf
low 118 mulxovi integer multiply int and exit on overf
low 119 addjovi integer add int and branch on overf
low 120 subjovi integer subtract int and branch on overf
low 121 muljovi integer multiply int and branch on overf
low 122 addjovq quad 64 bit add quad and branch on overf
low 123 subjovq quad 64 bit subtract quad and branch on overf
low 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 fol
lows: 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 fol
lowing 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 al
lows 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 fol
lowing 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 al
lowed. 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 al
low 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 fol
lows: 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 fol
lowing 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 fol
lowing 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 s
lower 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 al
lowed 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 fol
lowing 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 al
lowed. the checks performed are: if the principal originating the load is the system principal, the load is al
lowed. 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 al
lowed. 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 al
lowed. 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 al
lowed. ...
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. fol
low 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 fol
low 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 fol
low 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. be
low fol
lows 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 fol
lowing 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 ref
low 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: verifyref
low 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: verifyref
low 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. be
low 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 be
low 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 fol
lowing 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 fol
lowing preferences affect, there are a few things you should know. the data f
lows in gecko as fol
lows: 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 al
lows 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 f
low 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 fol
lowing 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 be
low 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 be
low 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 overf
low. --> <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; overf
low: visible; margin: 1em 1em; padding: 0.5em 0.5em; border: 2px solid blue; background-color: yel
low; 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 fol
lowing 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 al
lowing 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 fol
lowing 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 al
lowing 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 fol
lowing 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 al
lowed to access the chrome above it. content-primary the primary browser for content. the content that is loaded inside the browser is not al
lowed 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 be
low 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 al
low elements to be stacked above other elements yet al
low mouse events to be sent to
lower elements. in the fol
lowing 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 fol
lowing 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 fol
low 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 al
lows 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 al
low 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 be
low 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 be
low the desktop directory. these directories do not need to exist yet, but they can be created using nsifile.create(). see creating directories be
low 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 be
low 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 be
low 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 al
lows 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 fol
lowing 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 fol
lowing 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
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 fol
lowing 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 al
lows 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 fol
lowing 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 be
low 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 al
low 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 fol
lowing 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 be
low 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 be
low 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 be
low 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 // fol
low 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 al
lows 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 fol
lowing (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 fol
lows the same method for any type of content. however, the nature of menus can make this tricky to fol
low. 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 s
lower 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 fol
lowing 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 al
lows 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 fol
lowing 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 fol
low arcs or arrows in the rdf graph. the predicate attribute specifies the labels of the arrows to fol
low. 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 fol
low 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 al
low 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 fol
low the arrows in the forward direction. here is the rdf graph again: starting at node a and fol
lowing 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 fol
lowing: <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 fol
lowing, 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 fol
lowed 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 f
low 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 al
lows 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 be
low 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 fol
lowing syntax: <button id="identifier" class="dialog" label="ok" image="images/image.jpg" disabled="true" accesskey="t"/> the attributes are as fol
lows, 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 be
low shows how to do this. <button id="find-button" label="find"/> note: firefox does not al
low 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 fol
lowing 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 al
lows 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 fol
lowing 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. be
low, 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 al
lows 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 be
low 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 fol
lowing 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 be
low 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 be
low 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 fol
lowing 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 fol
low 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 al
lows 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 al
lows 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 al
lows 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 be
low 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 al
low 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 fol
lowing 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="yel
low"/> <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 fol
lows: 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 be
low. 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 be
low. <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 al
low 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 fol
lowing 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 fol
lowing 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 fol
lowing: 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 be
low. command updaters a command updater is a feature of the commandset element which al
lows 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 be
low. 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 fol
lowing 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 al
lowing 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 al
low 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 al
lows 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 be
low 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, , al
lowevents, , 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
« 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, , al
lowevents, , 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
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, , al
lowevents, , 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, , al
lowevents, , 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, , al
lowevents, , 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 be
low 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 fol
lowing 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 al
lowed 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 al
lowed 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 be
low: 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 fol
lowing 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, , al
lowevents, , 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, , al
lowevents, , 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 al
lowed 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, , al
lowevents, , 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 al
lowed 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 be
low you can set the type attribute to one of the values be
low 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
"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 fol
lowing 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 fol
lowing: 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 be
low 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 be
low 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, , al
lowevents, , 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
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, , al
lowevents, , 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, , al
lowevents, , 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, , al
lowevents, , 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
« 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, , al
lowevents, , 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, , al
lowevents, , 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
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, , al
lowevents, , 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, , al
lowevents, , 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 al
lowed 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 al
lows 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
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, , al
lowevents, , 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, , al
lowevents, , 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, , al
lowevents, , 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, , al
lowevents, , 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, , al
lowevents, , 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
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, , al
lowevents, , 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 fol
lowing 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, , al
lowevents, , 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, , al
lowevents, , 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, , al
lowevents, , 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, , al
lowevents, , 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 al
lowevents="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, al
lowevents, al
lownegativeassertions, 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 al
lowevents attribute did not work for title bars prior to firefox 3. properties inherited properties align, , al
lowevents, , 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 fol
lowing 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 be
low 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 fol
lowing 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, , al
lowevents, , 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, , al
lowevents, , 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, , al
lowevents, , 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, , al
lowevents, , 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, , al
lowevents, , 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, , al
lowevents, , 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
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, , al
lowevents, , 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 disal
low 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 disal
low 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 al
lows 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 s
low 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 fol
lowing .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 fol
lowed 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 fol
lowing 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 al
lows lack of required predictability al
lows 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 al
lows 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 al
lows for calls to setdatelist. if an implementation returns true for this attribute, it must al
low 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 al
lows you to create shortcuts to a particular address. the button gets added to the toolbar, separate from the links. ref
low branch build failed with vc 7.1 sp1 november 8th: roy received an error when he tried to ref
low 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 al
lows 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 be
low 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 yel
low 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 fol
lowing 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 fol
lowing 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 fol
lowing tables list the api names defined for specific w3c dom apis and lists the percentage of names that your browser actually defines fol
lowed 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 overf
low 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: 'overf
low', '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 be
low 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 al
lowed 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 al
lowed: for...of and if the for-of iteration is always the first component. multiple for-of iterations or if statements are al
lowed. 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 fol
lowing 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 al
low you to activate part of a file. to do so, add an exclamation point (!) to the end of the file name and fol
low 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 fol
low 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 be
low 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 fol
lowing is a comparison between the june 1998 version of ecma-262 and javascript 1.3. the fol
lowing 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 al
lowed. 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 al
lows 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 be
low (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 be
low. // 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 be
low. // 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 fol
lowing 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 fol
lowing 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 fol
lowing invariants are violated, the proxy will throw a typeerror: the enumerate method must return an object. examples the fol
lowing 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 fol
lowing 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 fol
lowing 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 al
lowed 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 al
lows 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 fol
lowing 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_c
lown_trigger.jpg" alt="c
lown trigger" border="0" width="150" height="115"> <h3>c
lown trigger</h3> <p> our c
lown 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 f
lowing 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 f
low 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 be
low 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 fol
lowing 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.to
lowercase() === '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 fol
lowing 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 al
lows 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 al
lowed 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
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 al
lows 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 fol
lowing 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 al
lows 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', al
lows 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 al
lows 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 fol
lowing 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 al
lows an address to be marked as being, for example, a work address for receiving parcels. the street-address property is plural as well. this al
lows 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 fol
lowed 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 al
lows 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 be
low 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 be
low 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 fol
lowing 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 al
low 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 fol
low 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 al
low 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 fol
lowing be
low 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 be
low 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 al
lowing the ball to bounce off all four walls, let's only al
low 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 fol
lowing: 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 fol
lowing line be
low 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 be
low, 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 be
low: 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 fol
lows: 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 be
low, 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 be
low 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 fol
lowing lines just be
low 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 be
low, 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 fol
lowing 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 be
low, 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 be
low. 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 be
low, 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 fol
low 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 fol
lows: 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 — al
lows 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 fol
lowing line be
low 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 be
low, 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 al
lowing 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 al
lowing 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-al
low-origin indicates whether the response can be shared. access-control-al
low-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-al
low-origin indicates whether the response can be shared. access-control-al
low-credentials indicates whether or not the response to the request can be exposed when the credentials flag is true. access-control-al
low-headers used in response to a preflight request to indicate which http headers can be used when making the actual request. access-control-al
low-methods specifies the method or methods al
lowed 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 fol
lows: 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. be
low 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 al
low 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 fol
low 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 al
lowing 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 al
low 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 al
lows it, then it will respond to the preflight request with an access-control-al
low-methods response header, which lists delete: http/1.1 204 no content connection: keep-alive access-control-al
low-origin: https://foo.bar.org access-control-al
low-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 s
low website or app script s
lows 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 al
lows s
low, 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 al
lows 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 ...
... ...
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 f
low 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 ref
low 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 s
low 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 be
low 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 be
low 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 be
low 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 be
low, 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 overf
lowing 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 be
low 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 be
low 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 be
low. try updating the live code be
low 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 be
low: try updating the live code be
low 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 be
low, 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 be
low 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 be
low 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 be
low 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 be
low 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
the fol
lowing 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 al
lows 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 be
low 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 al
low 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 fol
lowing 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 s
lowly, 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 al
lowed 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 be
low. 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 ys
low 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 fol
lowing: 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 al
low 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 be
low). 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; overf
low : 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%; overf
low : hidden; white-space : nowrap; text-overf
low : 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 */ overf
low-y: auto; overf
low-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; overf
low : 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%; overf
low : hidden; white-space : nowrap; text-overf
low : 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 */ overf
low-y: auto; overf
low-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; overf
low : 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%; overf
low : hidden; white-space : nowrap; text-overf
low : 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 */ overf
low-y: auto; overf
low-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 be
low 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 be
low 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 fol
lowed, 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, fol
lowed by a dot, fol
lowed 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, fol
lowed 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 overf
low. 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 be
low, 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 be
low 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 be
low 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 fol
lowing 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 al
low 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 al
lows 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 al
lows 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, al
lowing 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 fol
lows 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 fol
lowing 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 be
low 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 be
low 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 fol
lowing 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 be
low, 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 be
low 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 be
low 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 be
low, 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 be
low 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 be
low 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 be
low 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 fol
lowing 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 al
low 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 al
low 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 fol
lowing 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 be
low 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 fol
lowing: 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 be
low, 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 be
low, 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 be
low to recreate the finished example, fol
lowing 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 be
low to recreate the finished example, fol
lowing 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 be
low 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 fol
lows 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 al
low 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 al
lows 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 fol
lowing 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 be
low. 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 be
low: <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 al
low 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 al
low 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 fol
lowing 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 fol
lowing 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 fol
lowing: 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 s
lower. 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 fol
lowing 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 s
low 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 al
low a single management interface for high level objects. testopia al
lows users to login to one tool and uses bugzilla group permissions to limit access to modifying test objects. testopia al
lows 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 al
lows 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 fol
lowing 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-overf
low,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 (s
low on x86 / crash on arm) than undefined behavior float-cast-overf
low, 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 overf
low 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. be
low 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 al
low 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 fol
lowing 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 s
lower 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 fol
lowing 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 s
low 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 be
low), 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 fol
lowing 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 fol
lowing 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 al
lowdelayedload 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 fol
lowing 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 fol
lowing flags: sanitizeral
lowstyle sanitizeral
lowcomments 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 disal
lows 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, be
low 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 be
low: 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 fol
lows 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 al
lows 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 al
low mozilla to be used with a nanox server. activex control: an activex control al
lowing for embedding the gecko layout engine.obsolete since gecko 7.0 llmozlib & ubrowser: a static library that al
lows 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 fol
low. 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 be
low versions, you can find other versions (including beta) here: xulrunner releases (files include "sdk" in the name). the sdk fol
lows 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 fol
lowing 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 fol
lowing: 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 fol
lowing: 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 al
low 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 al
lows 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 fol
lowing 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 fol
lowing 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 launchwebf
low(); teardown(); attributes parameters object returns the set of parameters that initialized the firefox accounts oauth f
low. oncomplete function gets called when the firefox accounts oauth f
low 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 f
low. 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 launchwebf
low() 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.launchwebf
low(); ...
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 fol
lowing 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 fol
lowing 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 be
low. 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 f
low 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 be
low: 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 fol
lowing 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 be
low 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 be
low. 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 fol
low 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 fol
lowing 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 al
lows javascript code to call native libraries without requiring the development of an xpcom component. customizableui.jsm al
lows 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 al
lows 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 al
lows 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 be
low 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 be
low 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 fol
lowing 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 al
lows localization text to expand and not be truncated or resolved through ellipsis. title on the final page (meaning no more click through) should al
low 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 be
low 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 be
low 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 fol
lowing: 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 be
low). 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 fol
low 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 al
lows 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 fol
lowing 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 fol
lowing 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. al
lows us to understand how each l10n team is performing their localization work. al
lows 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 fol
low 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 fol
low 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 fol
lowing 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 fol
low 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 be
low. 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 be
low). 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 fol
lowing 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 fol
lowing 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 fol
lowing: <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 al
lowed 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 fol
lowing 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 al
low 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 al
lowing 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 fol
lows 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 s
low 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 s
low. 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, al
lowing 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 al
lows 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 fol
lowing 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 al
lows 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 fol
lowing 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 fol
low 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 al
low 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 fol
low 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 fol
lowing 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 al
lows 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 fol
lowing 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 - al
lows you to specify a new name for the profile. version - al
lows 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 al
lowed in the translation as well. consider the fol
lowing source html: <p data-l10n-id="save"> <input type="submit"> <a href="/main" class="btn-cancel"></a> </p> assume the fol
lowing 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 al
lowed in the translation. the value attribute is al
lowed on input elements, but type is not. similarly, href and onclick attributes are not al
lowed 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 be
low. 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 fol
lowing options set: ac_add_options --enable-debug ac_add_options --enable-trace-malloc running the tests in your <objdir> run the fol
lowing 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 be
low): 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", "al
lowclipboard"); user_pref("capability.policy.al
lowclipboard.sites", "https://www-archive.mozilla.org"); user_pref("capability.policy.al
lowclipboard.clipboard.cutcopy", "allaccess"); user_pref("capability.policy.al
lowclipboard.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.al
lowclipboard.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.al
lowclipboard.sites", "http://www-archive.mozilla.org") is not the same as: user_pref("capability.policy.al
lowclipboard.sites", "https://www-archive.mozilla.org") this is because the first uses http while the second uses https. if you want to al
low multiple urls to access the paste operation, separate the urls with a space. ...
...ref("capability.policy.al
lowclipboard.sites", "http://www-archive.mozilla.org") is not the same as: user_pref("capability.policy.al
lowclipboard.sites", "https://www-archive.mozilla.org") this is because the first uses http while the second uses https. if you want to al
low multiple urls to access the paste operation, separate the urls with a space. for example: user_pref("capability.policy.al
lowclipboard.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 al
low 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 fol
lowing 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 be
low. level is a numeric value between 0 and 5, with the values having the fol
lowing 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 fol
lows: 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 s
low 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 al
lowed to overf
low. 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 fol
lows: 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 fol
lows: 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 al
lowed 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 overf
low 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 fol
lows: struct prpolldesc { prfiledesc* fd; print16 in_flags; print16 out_flags; }; typedef struct prpolldesc prpolldesc; the structure has the fol
lowing 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 s
lower. 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. be
low 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 fol
lows: 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 al
low 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 al
low 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 al
lowed 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 fol
lowing 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 fol
lowing: 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 fol
lows: 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 fol
lowing 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 fol
lows: 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 be
low. 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 fol
lowing 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 fol
lowing: 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 be
low. 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 fol
lowing 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 fol
lowing: 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 be
low. 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 fol
lowing 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 fol
lowing: 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 fol
lowing 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 fol
lowing:</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 al
lows 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 hol
loway, 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 be
low. 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 fol
lowing 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 fol
lowing 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 be
low. (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 fol
lowing 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 be
low. 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 fol
lowing 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 fol
lowing 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 al
lowed/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 fol
lowing 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 al
lows 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 be
low. 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 fol
lowing 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 be
low. 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 fol
lowing 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 be
low. 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 fol
lowing 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 fol
lowing ca certificate was removed: cn = comsign sha-256 fingerprint: ae4457b40d9eda96677b0d3c92d57b5177abd7ac1037958356d1e094518be5f2 the fol
lowing 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 - al
low 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 fol
lowing 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 overf
low 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 - al
low 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 - al
low nss-try to be used to test nspr changes bug 1267894 - libssl should al
low 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 al
lowed by policy, but an application may al
low more by policy explicitly: config="al
low=curve1:curve2:hash1:hash2:rsa-1024..." only the specified hashes and curves will be al
lowed: config="disal
low=all al
low=sha1:sha256:secp256r1:secp384r1" only the specified hashes and curves will be al
lowed, and rsa keys of 2048 or more will be accepted, and dh key exchange with 1024-bit primes or more: config="disal
low=all al
low=sha1:sha256:secp256r1:secp384r1:min-rsa=2048:min-dh=1024" a policy that enables the aes ciphersuites and the secp256/384 curves: config="al
low=aes128-cbc:aes128-gcm::hmac-sha1:sha1:sha256:sha384:rsa:ecdhe-rsa:secp256r1:secp384r1" turn off md5 config="disal
low=md5" turn off md5 and sha1 only for ssl con...
...d, and dh key exchange with 1024-bit primes or more: config="disal
low=all al
low=sha1:sha256:secp256r1:secp384r1:min-rsa=2048:min-dh=1024" a policy that enables the aes ciphersuites and the secp256/384 curves: config="al
low=aes128-cbc:aes128-gcm::hmac-sha1:sha1:sha256:sha384:rsa:ecdhe-rsa:secp256r1:secp384r1" turn off md5 config="disal
low=md5" turn off md5 and sha1 only for ssl config="disal
low=md5(ssl):sha1(ssl)" disal
low values are parsed first, and then al
low 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 disal
lowing 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 fol
lowing styles are al
lowed: 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 fol
lows: /* * line1 * line2 */ or /* ** line 1 ** line 2 */ the fol
lowing 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 overf
low 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 fol
lowing 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 be
low. background on cert extensions an extension has the fol
lowing 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 fol
lowing 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 be
low. 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 fol
lowing: 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 fol
lowing: ssl v3. the secure sockets layer (ssl) protocol al
lows 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, al
lowing 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 al
lows 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 al
lows 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 fol
low 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 al
low all possible combinations of choices from those categories to be used. instead, tls al
lows 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 fol
lows: /* 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 fol
lows: 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 al
lows 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 al
lows 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 fol
low 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 al
low 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 fol
lowed 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 al
lows 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 be
low. 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 al
low 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.) al
lows. 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 al
low 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 s
low, 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 s
lowest. 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 s
low 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 al
lows 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 fol
lows (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, be
low. 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 fol
lowing 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 be
low. 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 al
low 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 fol
lowing 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 fol
lowing 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 be
low, 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 fol
lowed by alternating jsgc_mark_end and jsgc_finalize_end callbacks, fol
lowed 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 fol
lows 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 be
low. 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 fol
lowing 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 be
low. 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 fol
lowing 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 be
low. 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 fol
lowing 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 be
low. 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 be
low. 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 fol
lowing 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 be
low. 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 al
low 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 s
low tests and cover the most important options: jit_test.py --no-s
low 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 al
lows 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 fol
lowing 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 be
low 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 s
lower 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 al
lows to aggregate name from subtree of element then generate name from subtree of the element description the fol
lowing 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 al
lows 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 al
low 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
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 ('\\' fol
lowed 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 be
low). 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 fol
lowing 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 fol
lowing 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 al
lows the user to specify which users can view the activity, and (fol
lowing 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 al
lowed 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 al
lowed 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
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 be
low. 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, fol
lowed by at least one .ondataavailable(...) call, fol
lowed 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 fol
lowing 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 fol
lowing 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 be
low. 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: stackoverf
low :: 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 al
low everything inside profile-before-change to continue using it. profile-before-change-telemetry called to shut down telemetry, again separated to al
low 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 al
low you to modify headers and such. see this code snippet to learn how to get the tab that issued the request. http-on-opening-request similar to http-on-modify-request, but called earlier (synchronously during the channel's asyncopen() call), and some channel attributes (proxyinfo) may be missing. use only if your observer must be called before asyncopen returns. 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 al
low 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 al
low 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 al
low 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 al
low 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 al
low 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 al
low 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 fol
lowing 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 (be
low). 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 al
lowed 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 al
lowed 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 al
lowed 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 be
low 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 be
low. 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 al
low 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 al
low 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 al
low 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 al
lowed. 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 al
lows 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, fol
lowed 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, fol
lowed 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, fol
lowed 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, fol
lowed 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, fol
lowed 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, fol
lowed 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 al
lowed. 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. istabmodalpromptal
lowed 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 fol
lowing 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 al
low 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_al
low, 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 be
low 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 fol
lowing 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 fol
lowing 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 al
low 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 al
low 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 fol
lowing 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. forceal
lowthirdpartycookie 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 be
low the quoted message. (1 - replies appear above the quoted message. 0 - replies appear be
low 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 fccreplyfol
lowsparent 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 fol
lowing 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 fol
lowing 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 be
low. 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, fol
lowed 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, fol
lowed 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 be
low. 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, al
lows 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 s
lower, 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 al
lowed. 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 al
low 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 al
lowed values. aflag pass true if the event was blocked or false if it was al
lowed. 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 al
lowed 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 al
lowed 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. al
lows 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. al
low_action 1 permission is al
lowed. 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 fol
lowing 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 al
lowed to load the network resource located at the given uri under the same-origin policy. this means that codebase principals are only al
lowed to load resources from the same domain, the system principal is al
lowed to load anything, and null principals are not al
lowed 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 al
lowed this function does nothing. if the load is not al
lowed 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 al
lowed. 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 be
low. 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 fol
lowing: "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 fol
lowing "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 al
lows 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 fol
lowing 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 fol
lowing 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 al
lowed to perform. two examples: code that has the "universalxpconnect" capability is al
lowed 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 al
lowed to perform. two examples: code that has the "universalxpconnect" capability is al
lowed 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 al
lowed to perform certain actions that al
low it to read information from the local system. for example, this capability al
lows 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 al
low 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. fol
lowing 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 disal
lowed (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 al
low 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 fol
lows: 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" be
low). 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 al
low all interested parties a chance to act on each event. implementing nsistreamlistener the nsistreamlistener passed to setnewlistener() should implement the fol
lowing 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 al
low 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 fol
lowing 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. fol
lows 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 fol
lows 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, al
lowing 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 al
lowinvalid, in boolean al
lowduplicatenicknames, out boolean canceled); methods pickbyusage() nsix509cert pickbyusage( in nsiinterfacerequestor ctx, in wstring selectednickname, in long certusage, in boolean al
lowinvalid, in boolean al
lowduplicatenicknames, out boolean canceled ); parameters ctx selectednickname certusage al
lowinvalid al
lowduplicatenicknames 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_al
low_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_f
lowed 64 for plain text output. output for format f
lowed (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 be
low 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 fol
lowing 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_al
low_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_al
low_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 fol
lowing 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 fol
lowing 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 al
lowed 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, al
lowing 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 fol
lows.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 be
low.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 be
low 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 fol
lowing: 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 fol
lowing 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 fol
low 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 fol
low 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 fol
lows: 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 be
low xpcom; particularly, code xpcom could exploit, e.g., expat berkeley db changes to apis, functionality, and implementations the fol
lowing 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 al
lows xpconnect to convert function parameters and build the nsxptcvariant array required to make this call. the stubs (or impersonation) facility of xptcall al
lows 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 al
low 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 fol
lowing 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 fol
lowing 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 al
lows for very small stubs. however, the __stdcall requires the callee to clean up the stack, so it is imperative that the interface information scheme al
low 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
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 fol
lowed 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 al
low 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 be
low. 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 al
lows 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 al
lows 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 al
lowing 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 (stackoverf
low :: 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 al
lows 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 fol
lowed 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 al
low 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 al
lowing 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 al
lowing 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 al
low 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 al
low 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 al
low 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 al
low 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 al
lows 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 al
low 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 fol
lowing 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 fol
lowing: 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, al
lowing 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. be
low 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 al
lows 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 fol
lowing 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". be
low 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 al
lows 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 al
lows you to see the fol
lowing 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 be
low 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 be
low the css rules pane. having the css rules in their own pane is very useful because it al
lows 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 fol
lowing 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 s
low 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 be
low 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 fol
lowing 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 "ref
low". 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 f
low. 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 be
low 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 fol
lowing 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 al
low 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 fol
lowing 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 fol
lowing 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}, be
low). 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}, be
low). this associates the signal and controller with the fetch request and al
lows us to abort it by calling abortcontroller.abort(), as seen be
low 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
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 fol
lowing 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 fol
lowing 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 al
low 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 be
low 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
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 al
lowed only if there is at least one delaynode in the cycle. otherwise, a notsupportederror exception is thrown. this parameter is not al
lowed if the destination is an audioparam. return value if the destination is a node, connect() returns a reference to the destination audionode object, al
lowing 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 s
low 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 al
low 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 fol
lowing 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 fol
lowing 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 fol
lowing 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
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 fol
lowing 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 fol
lowing 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 fol
lowing 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 al
lows 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 al
lowing 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 — al
lows the registration of css custom properties, al
lowing for property type checking, default values, and properties that do or do not inherit their value. registering a custom property registering a custom property al
lows you to tell the browser how the custom property should behave; what are al
lowed 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 al
lows you to tell the browser how the custom property should behave; what are al
lowed 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 fol
lowing 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 fol
lowing 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 fol
lowing javascript: const allcomputedstyles = document.queryselector('button').computedstylemap(); the fol
lowing 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 s
low 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 al
lows 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 al
lows 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 fol
lows. 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 fol
lowing 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 be
low 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 al
lowed. <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 be
low. 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 fol
lows. 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 al
lows 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 fol
lowing 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 fol
lowing 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 be
low 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 f
low 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 al
low 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 fol
lowing 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 be
low. 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 fol
lowing methods alter the original matrix. dommatrixreadonly.flipx() returns a new dommatrix created by flipping the source matrix around its...
DOMParser - Web APIs
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, al
lowing 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, al
lowing you to go through all keys of the key/value pairs contained in this object. domtokenlist.values() returns an iterator, al
lowing 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, al
lowing you to go through all keys of the key/value pairs contained in this object. domtokenlist.values() returns an iterator, al
lowing you to go through all values of the key/value pairs contained in this object. examples in the fol
lowing 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="al
lowdrop(event)"> <span id="drag" draggable="true" ondragstart="drag(event)">drag me to the other box</span> </div> <div id="div2" ondrop="drop(event)" ondragover="al
lowdrop(event)"></div> css content #div1, #div2 { width:100px; height:50px; padding:10px; border:1px solid #aaaaaa; } javascript content function al
lowdrop(al
lowdropevent) { al
lowdropevent.target.style.color = 'blue'; al
lowdropevent.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 be
low) 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 fol
lowing 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 al
low-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: al
low 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 al
lowable 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 “al
low” or “al
low on any site” the request is resolved. if the user clicks “don’t al
low”, the storage access request is rejected and the requesting origin can re-request once it receives another user interaction. if the user al
lows 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 ref
low) 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 ref
low 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 al
lows 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 fol
lowing 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
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. nomodificational
lowederror 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,"<") + "</pre>"; operational details what exactly happens when you set value of innerhtml? doing so causes the user agent to fol
low 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 fol
lowing css styles our example content. .box { width: 600px; height: 300px; border: 1px solid black; padding: 2px 4px; overf
low-y: scroll; overf
low-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 be
low 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 fol
lowing 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
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 fol
lowing 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 fol
lowing 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 fol
lowing 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 al
lows 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 fol
lows: 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 be
low 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 al
lows 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 fol
lows: 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 be
low 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 be
low 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 fol
lowing 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 fol
lowing 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 fol
lowing: 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 al
lows 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 fol
lows: 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 al
lowfullscreen attribute in order to opt-in to al
lowing 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 al
low 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
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 fol
lowing 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
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 fol
lowing 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 al
lowed 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 fol
lowing 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 fol
low your mouse. it uses the onmousemove, onmouseover, and onmouseout event handlers. html <p><a href="#" data-tooltip="first link">see a tooltip here …</a></p> <p><a href="#" data-tooltip="second link">… 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">… 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.fol
low = 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 fol
lowing 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 fol
lowing properties are now obsolete: charset, coords, name, rev, and shape. the fol
lowing 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 fol
lowing 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 fol
lowing property is now obsolete: nohref. the fol
lowing 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 fol
lowing 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 be
low, 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 = 'yel
low'; 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 fol
low-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 fol
low-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 fol
low-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 be
low. .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 '/' fol
lowed by the path of the url. htmlhyperlinkelementutils.search this is a usvstring containing a '?' fol
lowed by the parameters of the url. htmlhyperlinkelementutils.hash this is a usvstring containing a '#' fol
lowed 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 be
low, 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 be
low 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 be
low. 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 be
low, 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 be
low 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 be
low. 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 be
low 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 be
low 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 al
low 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 al
lowing to access properties of the <legend> elements. it inherits properties and methods from the htmlelement interface. ...
... the htmllegendelement is an interface al
lowing 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 fol
lowing 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: notal
lowederror the user agent (browser) or operating system doesn't al
low 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 al
low automatic or script-initiated playback of media, calling play() will cause the returned promise to be immediately rejected with a notal
lowederror. 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 s
lower 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 al
lowed 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 fol
lowing 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 al
lowed 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 al
lows 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 fol
lowing 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 be
low, 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 be
low, 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 fol
lowing rules the prefix data- is removed (including the dash); for any dash (u+002d) fol
lowed 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) fol
lowed 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 fol
lowing rules: restriction: before the transformation, a dash must not be immediately fol
lowed 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, fol
lowed 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 fol
lowing 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 fol
lowing 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 al
low 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 al
low 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 fol
lowing 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 fol
lowing 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 fol
lowing values: "void", "above", "be
low", "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 fol
lowing 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 fol
lowed 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 al
low 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, al
lowing 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 be
low. 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 fol
lowing 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_al
lowed_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 fol
lowing code: not_al
lowed_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, al
lowing 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 fol
lowing 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
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 fol
lowing 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 fol
lowing 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 fol
lowing type: exception description invalidstateerror the transaction has already been committed or aborted. example in the fol
lowing 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
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 fol
lowing 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 be
low 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 fol
lowing 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 be
low) <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 al
lowed.</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
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 fol
lows 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 be
low. 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 al
lows 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 fol
lowing: 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 fol
lows: 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 be
low. 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", "yel
low", "green" ], // offset: 0, 0.5, 1 }, 2000); the special keys offset, easing, and composite (described be
low) 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 be
low. the fol
lowing 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-al
low-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 fol
lowing 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-al
low-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 fol
lowing 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() al
lows 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 al
low 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 al
lows to retrieve some metadata about the locked file. ...
...getmetadata method al
lows 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 fol
lowing 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 fol
lowing 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 be
low, 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 f
lows, 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
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 fol
lowing 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 fol
lowing 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 disal
low 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 fol
lowing 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 al
lows 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 al
lowed 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 fol
lowing 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 be
low 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 s
lower!). 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 fol
lowing 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 fol
lows: 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
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 fol
lowing: aborterror the scan operation was aborted with abortsignal passed in options. notal
lowederror 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
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 al
lows 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 fol
lowing: aborterror the write operation was aborted with abortsignal passed in options. notal
lowederror 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 fol
lowing 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")}} be
low 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 fol
lowing 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 al
low 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 al
low the action. if the user al
lows 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 al
low 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 al
low 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 be
low. 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 fol
lowing 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 s
lows down the next navigation. there is nothing the next page can do to avoid this, so the new page seems s
low, even though it's the previous page's fault. the fol
lowing 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 fol
lowing 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
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 al
lowing 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 al
lows web sites to register themselves as a possible handler for a given mime type. navigator.registerprotocolhandler() al
lows 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 fol
lowing 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 fol
lowing 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
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 fol
lows — 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 al
low notification permissions to be requested from cross-origin <iframe>s, with other browsers to fol
low. 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 fol
lows — 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 al
low notification permissions to be requested from cross-origin <iframe>s, with other browsers to fol
low. 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 disal
low 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 fol
lowing lines: from here the user can choose to al
low 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 al
low 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 fol
lowing 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 fol
lowing: 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 fol
lowing 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 fol
lows: 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 fol
lowing 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 fol
lowing: 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 be
low 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 be
low. 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()` be
low. 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 fol
lowing performanceentry properties by qualifying/constraining the properties as fol
lows: 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 fol
lowing performanceentry properties by qualifying/constrainting the properties as fol
lows: 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 fol
lowing performanceentry properties for resource performance entry types by qualifying and constraining them as fol
lows: 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 fol
lowing 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 fol
lowing 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 f
low. 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 f
low). // 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 be
low, 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 fol
lowing 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 be
low 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 be
low. 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 be
low. invalidmodificationerror one of the fol
lowing 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 al
lowed; 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 al
lows 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 fol
lowing 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 be
low. 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 al
lows 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 al
lows options to be set in the constructor when creating a reporting observer. available report types the spec defines the fol
lowing 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
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 al
low 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 al
low 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 fol
lowing 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 fol
lowing 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('f
lowers.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 fol
low 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 fol
lowing 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('f
lowers.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
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
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 — al
lows 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 fol
lowing 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('f
lowers.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, al
lowing 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 al
lowing 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 disal
lowing 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 be
low, 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 disal
lowing redirects be
low. 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; }); disal
lowing redirects because using redirected to manually filter out redirects can al
low 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
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 fol
lowing 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 fol
lowing 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_al
lowed_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_al
lowed_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 fol
lowing 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 fol
lowing 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 al
low) can specify a desire to use the screen capture api using the policy control directive display-capture: <iframe al
low="display-capture" src="/some-other-document.html"> the default al
low 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 fol
low. 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 al
low 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 al
lowed 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() al
lows 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 fol
lowing 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 al
low 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 be
low) 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 fol
lowing 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 al
lows 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 fol
lows: 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 al
lowed 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 be
low 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 al
lowed 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 fol
lowing 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
the request() method of the wakelock interface returns a promise that resolves with a wakelocksentinel object, which al
lows control over screen dimming and locking. syntax var wakelock = navigator.wakelock.request(type); parameters type options are as fol
lows: '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 notal
lowederror thrown when wake lock is not available, which can happen because: document is not al
lowed 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 notal
lowederror thrown when wake lock is not available, which can happen because: document is not al
lowed 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 fol
lowing 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 fol
lowing 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 be
low distortion curve code on stack overf
low. 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 be
low. 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 be
low. srcalpha a glenum specifying a multiplier for the alpha source blending factor. the default value is gl.one. for possible values, see be
low. 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 be
low. srcalpha a glenum specifying a multiplier for the alpha source blending factor. the default value is gl.one. for possible values, see be
low. dstalpha a glenum specifying a multiplier for the alpha destination blending factor. the default value is gl.zero. for possible values, see be
low. 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 be
low. 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 fol
lowing 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 fol
lowing 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 al
lowed 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 al
lowed 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 fol
lowing 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 be
low for possible values. return value depends on the parameter. parameter names webgl 1 you can query the fol
lowing 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 fol
lowing 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 al
lows 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 yel
low. 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 be
low 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 be
low 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 f
low 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, be
low 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 be
low. 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 f
low. 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 be
low 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 be
low 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 al
low 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 be
low 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 al
low 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, bufferedamount
lowthreshold, onbufferedamount
low, and bufferedamount
low 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 al
low 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 al
low 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 al
low 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 al
lows 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 fol
lowing 2 bytes (16-bit unsigned integer) are the length. if it is 127, the fol
lowing 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 { overf
low: auto; } #output > p { overf
low-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, al
lowing 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, al
lowing 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; s
lowing 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 al
lows 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 fol
lowing: 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 fol
lows: 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 be
low. 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 fol
lowing 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 fol
lows: const cat = localstorage.getitem('mycat'); the syntax for removing the localstorage item is as fol
lows: localstorage.removeitem('mycat'); the syntax for removing all the localstorage items is as fol
lows: 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. always
lowered if on, the new created window floats be
low, under its own parent when the parent window is not minimized. always
lowered windows are often referred as pop-under windows. the always
lowered window can not be on top of the parent but the parent window can be minimized. in ns 6.x, the always
lowered 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
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 al
lowed 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 fol
lowing 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 be
low, you can now access them via the retvals array after the opendialog() call returns. inside the dialog code, you can set the properties as fol
lows: 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 fol
lowing 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 ":" fol
lowed 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
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 be
low. 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 fol
lowing 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
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 fol
lows: 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 al
lowed 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 fol
lowing 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
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 fol
lowing 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 fol
lowing 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 fol
lowing: 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 be
low). 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 fol
lowing 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 be
low 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 fol
lowing 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 be
low 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 be
low 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 be
low, 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 al
lows 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 be
low: 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 fol
lowing 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 fol
lowing exceptions. these are true exceptions, since this method does not return a promise. invalidstateerror this may occur for one of the fol
lowing 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
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 be
low, 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 fol
lowing 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 fol
lowing 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 fol
lowing: 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 fol
lowing 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 fol
lowing 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. be
low 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 fol
lowing 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 f
low. 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 be
low 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 be
low, 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 be
low, 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 fol
lowing 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 be
low 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 f
low 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 be
low. 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 al
lows 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 al
low 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 overf
low 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 al
low keyboard-only users to scroll regions with overf
low text. svg role="region" can be declared on areas of svg along with an aria-label to al
low 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 f
low 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 be
low 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 fol
lowing: 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, al
lows 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 workf
low. ...
...t workf
low. 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 al
low 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 al
low 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 fol
lowing 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 al
lows 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 al
lows 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 overf
low 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 overf
low 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 overf
low 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; overf
low: hidden; } result specifications specification status comment css overf
low 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
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: yel
low; 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 overf
lowing text when form fields are too small, placeholder text can get cropped in an undesirable way. you can use the text-overf
low property to alter the way overf
lowing 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-overf
low: ellipsis; } result customized input field the fol
lowing example highlights the branch and id code fields with a custom style. html <form id=...
... working draft initial definition. ...
:valid - CSS: Cascading Style Sheets
the :valid css pseudo-class represents any <input> or other <form> element whose contents validate successfully. this al
lows 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 fol
lowing 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 be
low: 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
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: al
lowable 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. al
lowable svg attributes are fill and stroke. the alpha component of the al
lowed 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, al
lowing them to be styled with the :visited state */ background-color: white; border: 1px solid white; } a:visited { background-color: yel
low; 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 al
lowed 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
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 fol
lowing 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 be
low (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 al
lowable 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 al
lowed. 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 al
lowed. 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 fol
lowing 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 al
lows control over advanced typographic features in opentype fonts. font-variation-settings al
lows
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 al
lowing 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 be
low. 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 overf
low: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 be
low. 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 be
low 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; overf
low: 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 be
low 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 be
low 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 be
low, 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 al
low 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 al
lowed 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 f
lowed 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 overf
lowing 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 al
lowed 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 overf
low in multicol what happens when an item overf
lows 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
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 fol
lowing 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 fol
lows: 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 be
low would create an eight track grid, with a narrower 1fr width column named col1-start fol
lowed 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 fol
lowing 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 be
low 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-f
low: 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 fol
lowing 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-f
low: 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 f
low. ...
...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 f
low. the physical meaning of these terms depends on the writing mode. block dimension the dimension perpendicular to the f
low 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 f
low 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) overf
low-block overf
low-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 be
low 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 fol
lowing, 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 be
low 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 be
low 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 fol
lowing 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 fol
lowing 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 overf
low-clip-box overf
low-clip-box-block overf
low-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 be
low. 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 overf
low -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: yel
low; /* visited links have yel
low colored text */ } impact on web developers overall, these restrictions shouldn't affect web developers too significantly. they may, however, require the fol
lowing 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 fol
lowing 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 fol
lowing, 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 fol
lowing 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 fol
lowing, 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 fol
lowing 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 fol
lowing 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 fol
lowing, 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 be
low. ...
...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 be
low. values <line-style> describes the style of the border. it can have the fol
lowing 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
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 be
low. 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 fol
lowing 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 al
low 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 al
lows 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 be
low. 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
the clear css property sets whether an element must be moved be
low (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 be
low 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.0f
low-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 al
lowed 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 fol
lowing keywords. values economy the user agent is al
lowed 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 al
low 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 al
lowed 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 al
lowed 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
<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. al
lows 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 be
low. ...
...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 be
low. values none the element does not span multiple columns. all the element spans across all columns. content in the normal f
low 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
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 fol
lowing 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 be
low, 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 f
lowed, 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
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 al
low 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 be
low example makes use of the optional second parameter of env(), which al
lows 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 be
low 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 al
lowed. 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 al
lowed. 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 fol
lowing 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:yel
low;">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:yel
low;">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
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-f
low 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
the flex-wrap css property sets whether flex items are forced onto one line or can wrap onto multiple lines. if wrapping is al
lowed, 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 be
low. values the fol
lowing values are accepted: nowrap the flex items are laid out in a single line which may cause the flex container to overf
low. 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: yel
lowgreen; } .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
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 fol
lowing 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 be
low 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 al
lowed 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 be
low. 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 al
lowable 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 al
lowed 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 al
lowed between the number and the unit. 0 although unitless zero is an al
lowable <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 fol
lowing 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 al
lowed 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
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 be
low. 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 be
low 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 be
low for details. auto the browser is free to automatically break words at appropriate hyphenation points, fol
lowing whatever rules it chooses. however, suggested line break opportunities (see suggesting line break opportunities be
low) 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
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 fol
lowing: 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, \, fol
lowed 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 fol
lowed by alphanumeric characters --toto a custom-property like identifier _internal an underscore fol
lowed by alphanumeric characters \22 toto a unicode character fol
lowed 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 fol
lowed 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
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 be
low. 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 al
lows 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 fol
low this recommendation by placing the fol
lowing 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; /* overf
low 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 overf
lows 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> | <overf
low-position>? [ <self-position> | left | right ]where <baseline-position> = [ first | last ]? baseline<overf
low-position> = unsafe | safe<self-position> = center | start | end | self-start | self-end | flex-start | flex-end examples simple demonstration in the fol
lowing 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 hol
low 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 al
lows 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 fol
lowing 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 al
lows 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-f
low for in-f
low 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-f
low 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-f
low 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
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 al
lowed. <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 al
lowed. 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 fol
lows: 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
the source for this interactive example is stored in a github repository. if 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 al
low 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 al
lowed 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 be
low. values auto the default scroll overf
low behavior occurs as normal. contain default scroll overf
low 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 overf
low behavior occurs as normal. contain default scroll overf
low 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 overf
low 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; overf
low: 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 be
low. values auto the default scroll overf
low behavior occurs as normal. contain default scroll overf
low 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 overf
low behavior occurs as normal. contain default scroll overf
low 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 overf
low behavior is prevented. ...
...ouring scrolling areas, and default scroll overf
low 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; overf
low: 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 be
low. 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 overf
low behavior occurs as normal. contain default scroll overf
low 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 overf
low behavior occurs as normal. contain default scroll overf
low 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 overf
low 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; overf
low: 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
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 fol
lowing 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
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 overf
low 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 overf
low, 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-f
low 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 al
lowed 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 al
lowed 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 be
low. 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 be
low. 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 fol
low 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 overf
low-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 overf
low-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-f
low: column nowrap; font-family: monospace; } .container { display: flex; overf
low: auto; outline: 1px dashed lightgray; flex: none; } .container.x { width: 100%; height: 128px; flex-f
low: row nowrap; } .container.y { width: 256px; height: 256px; flex-f
low: 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 fol
lowing 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 fol
lowing 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 be
low 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. be
low forces the line to be be
low 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 be
low 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
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> fol
lowed by one of the units listed be
low. 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 fol
lows 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 al
lowed 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 al
lowed 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 fol
lowing example provides a 3d cube created from dom elements and transforms, and a select menu al
lowing 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 al
lowing 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 al
low 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 overf
low-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 be
low. 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 overf
low 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 be
low. ...
...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 be
low. values normal use the default line break rule. break-all to prevent overf
low, 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 overf
low-wrap: anywhere, regardless of the actual value of the overf
low-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 overf
low-wrap: anywhere, regardless of the actual value of the overf
low-wrap property. note: in contrast to word-break: break-word and overf
low-wrap: break-word (see overf
low-wrap), word-break: break-all will create a break at the exact place where text would otherwise overf
low 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 be
low: 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 al
low 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 al
low 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 al
low 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 al
low 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 al
lows us to set the playback rate before playing the media, while playbackrate al
lows 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 fol
lows: 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 be
low. 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 be
low. 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 fol
lows: const event = new customevent('build', { detail: elem.dataset.time }); this will then al
low 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 fol
lowing 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 fol
lowing 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 s
lower!). 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(); // al
low 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 fol
lows: 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 fol
lowing 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 be
low 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 fol
low 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 al
lows our layouts to benefit from the flexibility and future-readiness of responsive design. using user-agent detection specifically for content and not layout also al
lows 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 f
low 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 fol
lowing 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 al
lows 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 fol
lowing 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 fol
lowing 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
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 rangeunderf
low 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 fol
lowing 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 f
low content in html5. there are also additional categories, e.g. interactive content. elements the fol
lowing 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 f
low ...
<abbr>: The Abbreviation element - HTML: Hypertext Markup Language
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 f
low 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 f
low 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 be
low. 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
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 f
low 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. al
lowed 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 fol
lowed, 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 fol
lowing 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
, 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 f
low 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 fol
lowing 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
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 f
low content. tag omission the end tag can be omitted if the element is not immediately fol
lowed 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 fol
lowed 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 fol
lowing attributes are deprecated and should not be used. they are documented be
low 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 fol
lowing 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
(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 f
low 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 fol
lowed 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 al
lows 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
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 f
low content, sectioning root, palpable content. permitted content a <figcaption> element, fol
lowed by f
low content; or f
low content fol
lowed by a <figcaption> element; or f
low content. tag omission none, both the starting and ending tag are mandatory. permitted parents any element that accepts f
low 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 f
low of a document, but that can be moved to another part of the document or to an appendix without affecting the main f
low. 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
for this interactive example is stored in a github repository. if 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 f
low 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 be
low. nesting a <kbd> element inside a <samp> element represents input that has been echoed back to the user by the system. see echoed input, be
low, 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
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 f
low content, phrasing content, embedded content permitted content zero or more <source> elements, fol
lowed 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, fol
lowed by a w (such as 300w); or a pixel density descriptor, fol
lowed 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
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 f
low content tag omission none, both the starting and ending tag are mandatory. permitted parents any element that accepts f
low 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. ...
... <shadow></p>'; // insert into younger shadow root, including <shadow>. // the previous markup will not be displayed unless // <shadow> is used be
low. 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 fol
lowing. specifications this element is no longer defined by any specifications. ...
<sub>: The Subscript element - HTML: Hypertext Markup Language
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
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 f
low 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 be
low. 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
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, f
low 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 al
lowed 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 be
low. 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
the html <time> element represents a specific period in time. it may include the datetime attribute to translate dates into machine-readable format, al
lowing for better search engine results or custom features such as reminders. it may represent one of the fol
lowing: 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 f
low 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 be
low. 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 be
low). 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
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 f
low 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 al
lowed 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 al
lows two techniques so that it is clear for your users, or search engines, which domain is the canonical one, while still al
lowing 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 be
low to al
low 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. f
low 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 al
low 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
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 be
low. 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 be
low. 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 be
low. 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 fol
lows: 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 fol
lowing 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, al
lowing 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 fol
lowing 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 al
lowing 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 fol
lowing 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 s
low 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 fol
lowing 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 be
low. 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 al
lowed to gather information about the orientation of the device through the gyroscope interface. syntax feature-policy: gyroscope <al
lowlist>; <al
lowlist> an al
lowlist is a list of origins that takes one or more of the fol
lowing values, separated by spaces: *: the feature will be al
lowed in this document, and all nested browsing contexts (iframes) regardless of their origin. 'self': the feature will be al
lowed in this document, and in all nested browsing contexts (iframes) in the same origin. 'src': (in an iframe al
low attribute only) the feature will be al
lowed 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 al
lowed in this document, and in all nested browsing contexts (iframes) in the same origin. 'src': (in an iframe al
low attribute only) the feature will be al
lowed 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 al
lowed 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 al
lowed 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 al
lowlist, which is one of: *: the feature is al
lowed by default in top-level browsing contexts and all nested browsing contexts (iframes). 'self': the feature is al
lowed by default in top-level browsing contexts and in nested browsing contexts (iframes) in the same origin. the feature is not al
lowed 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 al
lowed to show layout animations. syntax feature-policy: layout-animations <al
lowlist>; <al
lowlist> an al
lowlist is a list of origins that takes one or more of the fol
lowing values, separated by spaces: *: the feature will be al
lowed in this document, and all nested browsing contexts (iframes) regardless of their origin. 'self': the feature will be al
lowed in this document, and in all nested browsing contexts (iframes) in the same origin. 'src': (in an iframe al
low attribute only) the feature will be al
lowed 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 al
lowed in this document, and in all nested browsing contexts (iframes) in the same origin. 'src': (in an iframe al
low attribute only) the feature will be al
lowed 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 al
lowed 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 al
lowed 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 al
lowlist, which is one of: *: the feature is al
lowed by default in top-level browsing contexts and all nested browsing contexts (iframes). 'self': the feature is al
lowed by default in top-level browsing contexts and in nested browsing contexts (iframes) in the same origin. the feature is not al
lowed 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 al
lowed to display images in legacy formats. syntax feature-policy: legacy-image-formats <al
lowlist>; <al
lowlist> an al
lowlist is a list of origins that takes one or more of the fol
lowing values, separated by spaces: *: the feature will be al
lowed in this document, and all nested browsing contexts (iframes) regardless of their origin. 'self': the feature will be al
lowed in this document, and in all nested browsing contexts (iframes) in the same origin. 'src': (in an iframe al
low attribute only) the feature will be al
lowed 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 al
lowed in this document, and in all nested browsing contexts (iframes) in the same origin. 'src': (in an iframe al
low attribute only) the feature will be al
lowed 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 al
lowed 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 al
lowed 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 al
lowlist, which is one of: *: the feature is al
lowed by default in top-level browsing contexts and all nested browsing contexts (iframes). 'self': the feature is al
lowed by default in top-level browsing contexts and in nested browsing contexts (iframes) in the same origin. the feature is not al
lowed 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 al
lowed to download and display large images. syntax feature-policy: oversized-images <al
lowlist>; <al
lowlist> an al
lowlist is a list of origins that takes one or more of the fol
lowing values, separated by spaces: *: the feature will be al
lowed in this document, and all nested browsing contexts (iframes) regardless of their origin. 'self': the feature will be al
lowed in this document, and in all nested browsing contexts (iframes) in the same origin. 'src': (in an iframe al
low attribute only) the feature will be al
lowed 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 al
lowed in this document, and in all nested browsing contexts (iframes) in the same origin. 'src': (in an iframe al
low attribute only) the feature will be al
lowed 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 al
lowed 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 al
lowed 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 al
lowlist, which is one of: *: the feature is al
lowed by default in top-level browsing contexts and all nested browsing contexts (iframes). 'self': the feature is al
lowed by default in top-level browsing contexts and in nested browsing contexts (iframes) in the same origin. the feature is not al
lowed 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 al
lowed to download and display unoptimized images. syntax feature-policy: unoptimized-images <al
lowlist>; <al
lowlist> an al
lowlist is a list of origins that takes one or more of the fol
lowing values, separated by spaces: *: the feature will be al
lowed in this document, and all nested browsing contexts (iframes) regardless of their origin. 'self': the feature will be al
lowed in this document, and in all nested browsing contexts (iframes) in the same origin. 'src': (in an iframe al
low attribute only) the feature will be al
lowed 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 al
lowed in this document, and in all nested browsing contexts (iframes) in the same origin. 'src': (in an iframe al
low attribute only) the feature will be al
lowed 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 al
lowed 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 al
lowed 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 al
lowlist, which is one of: *: the feature is al
lowed by default in top-level browsing contexts and all nested browsing contexts (iframes). 'self': the feature is al
lowed by default in top-level browsing contexts and in nested browsing contexts (iframes) in the same origin. the feature is not al
lowed 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 al
lowed to trigger device vibrations via navigator.vibrate() method of vibration api. syntax feature-policy: vibrate <al
lowlist>; <vibrate> an al
lowlist is a list of origins that takes one or more of the fol
lowing values, separated by spaces: *: the feature will be al
lowed in this document, and all nested browsing contexts (iframes) regardless of their origin. 'self': the feature will be al
lowed in this document, and in all nested browsing contexts (iframes) in the same origin. 'src': (in an iframe al
low attribute only) the feature will be al
lowed 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 al
lowed in this document, and in all nested browsing contexts (iframes) in the same origin. 'src': (in an iframe al
low attribute only) the feature will be al
lowed 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 al
lowed 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 al
lowed 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 al
lowlist, which is one of: *: the feature is al
lowed by default in top-level browsing contexts and all nested browsing contexts (iframes). 'self': the feature is al
lowed by default in top-level browsing contexts and in nested browsing contexts (iframes) in the same origin. the feature is not al
lowed 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 al
lows 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 al
lowed 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 al
lowed. 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 al
lowed. 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 be
low for more information. fixing common warnings samesite=none requires secure the fol
lowing 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 fol
lowing 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. al
low-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 be
low. 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 disal
lows 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 al
low 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 fol
lows: connection: upgrade upgrade: websocket websocket-specific headers the fol
lowing 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 al
lows 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 fol
lows. 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 al
lows 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
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 al
lowed 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 fol
lowed 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 fol
low 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 be
low, 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 al
lows 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 al
low 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 al
lows 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 al
lowing 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 al
low 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 fol
lowing 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 fol
lowing 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) fol
lowed 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 fol
lowed 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 fol
lowed 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 al
low 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 fol
lowing 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 fol
lowing 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 fol
lowing code at the beginning of your scripts, al
lowing 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 fol
lowed 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 al
lows 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 fol
lowing code at the beginning of your scripts, al
lowing 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 fol
lowing 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 fol
lowing 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 fol
lowing code creates the myfish array containing four elements, then removes its last element. var myfish = ['angel', 'c
lown', 'mandarin', 'sturgeon']; var popped = myfish.pop(); console.log(myfish); // ['angel', 'c
lown', 'mandarin' ] console.log(popped); // 'sturgeon' using apply( ) or call ( ) on array-like objects the fol
lowing 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', 'c
lown', 'mandarin' ] console.log(popped); // 'sturgeon' using apply( ) or call ( ) on array-like objects the fol
lowing 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:'c
lown', 2:'mandarin', 3:'sturgeon', length: 4}; var popped = array.prototype.pop.call(myfish); //same syntax for using apply( ) console.log(myfish); // {0:'angel', 1:'c
lown', 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 shal
low copy of elements from the original array. elements of the original array are copied into the returned array as fol
lows: 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 fol
lowing 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 fol
lowing code at the beginning of your scripts, al
lowing 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 fol
lows: 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 al
lowed by the specification. most notably, the ie and edge browsers insert bidirectional control characters around dates, so the output text will f
low 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 be
low): 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 fol
lowing 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 fol
lowing unicode extension key is al
lowed: 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 shal
low 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 shal
low 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 s
low 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 al
lows 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 fol
lowing code traps object.isextensible(). const p = new proxy({}, { isextensible: function(target) { console.log('called'); return true; } }); console.log(object.isextensible(p)); // "called" // true the fol
lowing 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 fol
lowing 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") al
lows . 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 fol
lowing 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 s
lower 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 be
low. 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 be
low. 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 be
low. 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 fol
lowing 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 fol
lows 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 fol
lows: 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 fol
lowing members: initial the initial size of the webassembly memory, in units of webassembly pages. maximum optional the maximum size the webassembly memory is al
lowed 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 fol
lowing 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 fol
lowing 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 fol
lowing example returns nan: parsefloat('ff2'); parsefloat and bigint the fol
lowing 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 fol
lowing 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. shal
low-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 al
lows 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 fol
lowing 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 fol
lows 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 fol
lowing 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 fol
lowing: 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 fol
lowing yield. examples using yield the fol
lowing 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 al
lows 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 al
lows 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 be
low). 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 fol
lowing. 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 be
low 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 s
lowly 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 fol
lowing with statement specifies that the math object is the default object. the statements fol
lowing 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 fol
lows: 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 al
lows 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 overf
low stack overf
low 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
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 fol
lowing 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. overf
low specifies how an expression behaves if it is too long to fit in the al
lowed 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 al
lowed, 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 be
low 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
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 fol
lowing: 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 s
lower 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 fol
lows the basic template be
low. 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 be
low: 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 fol
lowing 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 &, 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, ref
low, 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 s
lower 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 be
low 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 be
low, 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 fol
lowing 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 al
lows 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, al
lows 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 al
low 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 al
lows 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 al
lows 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 al
lows 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 — al
lowing 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 fol
lowing 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 al
low 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 al
lows 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
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 fol
lowing 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 fol
lowing 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 al
lows 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 fol
lowing 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
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 fol
lowing 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
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-f
lowto, 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
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-f
lowto, 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 al
lowed 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
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-f
lowto, 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
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 be
low). 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-f
lowto, 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 fol
lowing 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 fol
low 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 al
lows 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 be
low: 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 al
lowed on http://127.0.0.1/ (see bug 903966). chrome al
lows mixed content on http://127.0.0.1/ and http://localhost/. safari does not al
low 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 al
lows 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, al
lowing 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 fol
lowing 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 be
low 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 al
lowed to access content served from https://example.com/. wildcards are not al
lowed. 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 fol
lowing "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 fol
lowing 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 fol
lowing 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 be
low 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 be
low. 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 be
low 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 be
low: // 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 fol
lowing: 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 '/' fol
lowed 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 '#' fol
lowed 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 '?' fol
lowed 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 fol
lowing 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 fol
lowing 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); }, yel
low: function yel
low() { 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>', al
lowjavascript: 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 fol
lowing options are ignored. al
lowauth boolean whether to al
low auth dialogs. defaults to false. al
lowjavascript boolean whether to al
low javascript execution. defaults to false. al
lowplugins boolean whether to al
low 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 shal
low, 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 fol
lowed by an asterisk, as be
low. 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 fol
lowed 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 fol
lowed 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 fol
low 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 yel
low 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 fol
lowing would be to add chromewindow.prototype or window.prototype, accessing this.document.queryselector, or fol
lowing 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 fol
lowing arguments in place of the object: aurl a string url for the document to view the source of. apagedescriptor (optional) a "descriptor" that al
lows 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) al
lowed 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 al
low 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 be
low 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 be
low. 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.al
low_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 f
low 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 al
lowed 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 al
low 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 be
low 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 al
lowed 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 al
lows 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 al
lows javascript code to load functions from dlls on windows, and should al
low 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 fol
low 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 al
low 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 al
lows 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 fol
lows 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 s
lower 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 s
low 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 al
lows 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 fol
lowing 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 al
low 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 be
low, 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 fol
lowing 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 be
low 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 al
lowed to do certain unsafe things that user stylesheets are not al
lowed 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 fol
lows. 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 fol
lowing 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 be
low 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 al
low 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 fol
lows 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 fol
lowing 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 s
low, 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 fol
lowing 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 be
low. <!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 be
low 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 be
low 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 fol
lowing <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 fol
lows: 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 al
lows 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 fol
lowing 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 fol
lowing 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) al
lowed. 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 fol
lowing: [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 fol
lowing 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 fol
lowing 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 al
lows 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 f
low shuffling in nsuriloader. the prose description be
low 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: al
lows 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 be
low for the current implementation. the resultstring will either be a base-64 encoded popodeckeyrespcontent message, or one of the fol
lowing 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 al
low -- 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 al
lows 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 fol
lowing 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 fol
lowing 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 fol
lowing 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) al
lows 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 s
low 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 fol
low 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 al
lows 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 al
lows for some client-side web application styling. the web application bundle is al
lowed 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 al
lows 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 al
lows 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 fol
lowing: 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 be
low. 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 be
low, 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 fol
low 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 fol
lowing 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 be
low 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 al
low 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.al
low_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.al
low_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 "al
lowxulxbl", like this: components.classes["@mozilla.org/permissionmanager;1"] .getservice(components.interfaces.nsipermissionmanager) .add(uri, 'al
lowxulxbl', components.interfaces.nsipermissionmanager.al
low_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 al
low 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 fol
lowing 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 al
low use of your version of this file only * under the terms of either the gpl or the lgpl, and not to al
low 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 al
low use of your version of this file only * under the terms of either the gpl or the lgpl, and not to al
low 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 hel
loworld = "hello world"; * * addtestcase( * "var hel
loworld = 'hello world'", // description of the test * "hello world", // expected result * hel
loworld ); // actual result * */ // add your tests here var hel
loworld = "hello world"; addtestcase( "var hel
loworld = 'hello world'", "hello world", hel
loworld ); test(); // leave this alone. th...
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 fol
lowing steps. ...
... in order to ensure that changes to the tamarin code base are high quality before submitting, all developers are required to complete the fol
lowing 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 fol
lowing 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 al
low 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 al
low 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 al
lows the user interface be written in javascript and xul, which al
lows 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 fol
lowing 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 fol
low directives mentioned at venkman faq section 5.4 and then you may report a bug on javascript debugger component. rela...
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 be
low. 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 fol
lowing 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 fol
low the links be
low: 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 -- doronatnospamal
lowedherenetscape.com arun k. ranganathan -- aruneratnospamal
lowedherenetscape.com petter ericson -- petteratnospamal
lowedherecycore.com this is an install.js file that does the fol
lowing -- 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 fol
lowing 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 al
lows 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 be
low the minimum size due to the position of the splitter. ...
crop - 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 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 fol
lowing 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 be
low: 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 fol
lowing 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 be
low */ 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 be
lowpopupalign 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 be
low 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 fol
lowing 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 al
low 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 fol
lowing 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 fol
lowing 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 al
low 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 al
low 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
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 fol
lowing 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 al
low 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 fol
lowing 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 be
low, 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 al
low 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 fol
lowing 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 fol
lowing list other commands (prefixed by cmd_ or browser:) which have not been categorized here yet (though they are in the alphabetical list be
low): 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 al
lows 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 be
low? <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 fol
lowing 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 fol
lowing 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 fol
lowing example, pressing the 'view' button will open a menu which al
lows 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 be
low 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 be
low 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 al
low 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 fol
lowing, 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 yel
low 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 al
low 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 be
low 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 be
low: <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 fol
lowing 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 fol
lowing: <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 be
low. simple query conditions simple queries also use a simpler way of handling triple elements to filter out unwanted results. it al
lows 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 al
lowed. 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 fol
lowing: 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 al
lows 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 al
lows 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 fol
lowing 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 "overf
low: 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 be
low 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 be
low. 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 fol
lowing: 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
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 al
lows 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 fol
lowing 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 al
lows 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 al
low 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 fol
lowing syntax: <html:progress id="identifier" mode="determined" value="50" max="100"/> the attributes are as fol
lows: 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 be
low 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 be
low: 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 fol
lowing 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 al
low 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, fol
lowed 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 fol
lowing: 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 fol
lowing data model to illustrate how bindings work. see the rdf/xml file friends.rdf, be
low, 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 fol
lowing 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 fol
lowing the xml declaration as fol
lows. <?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 be
low 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 fol
lowing 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 be
low, 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 be
low 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 fol
lowing 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 be
low 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 fol
lowing 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
<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, al
lowevents, al
lownegativeassertions, 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, , al
lowevents, , 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
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 be
low 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 fol
lowing 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, al
lowevents, al
lownegativeassertions, 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, , al
lowevents, , 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
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 al
lowed 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 al
lows 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, al
lowevents, al
lownegativeassertions, 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, , al
lowevents, , 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 fol
lowing 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 al
lows 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 al
lowed 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 fol
lowing 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 fol
lowed 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 fol
lowing 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 al
lowing 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 fol
lowing 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 fol
lowing 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 fol
lows 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 fol
lowing 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 al
lowed and treated as an ordinary link. pcast: similar to feed: just differentiating between different types of feeds and should be al
lowed 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 al
lowed and treated as an ordinary link. pcast: similar to feed: just differentiating between different types of feeds and should be al
lowed 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 al
lowed as the security manager doesn't differentiate between access types. other this is for al
lowing protocol handlers to define a custom security model (see bug 120373). there is no consensus in the posts as to if this should be al
lowed. 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 ref
low branch off of trunk l. david baron announced that he merged the ref
low branch to a new branch (ref
low_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 (ref
low 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. ref
low branch testing wanted l. david baron would like users to test the ref
low 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:ref
low...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 al
lows 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 be
low). 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_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 fol
lowing 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 al
low 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 al
lows plug-ins to take advantage of any customized memory allocation scheme the application may have, and al
lows 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, fol
lowed 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 fol
lowing 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 be
low). 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 fol
lowing 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 fol
lows (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 al
lows a plugin to change the stored information associated with a url, in particular its cookies. (while the api theoretically al
lows 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 fol
lowing 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 al
low 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 fol
lowing 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 al
lows 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 fol
lowing 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 be
low). 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 fol
lowing 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 al
lows 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 f
low 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 fol
lowing 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 fol
lowed 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 fol
lows: 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 fol
lowing 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 fol
lowing: 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 al
low 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 al
lows 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> ...
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 fol
lows 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 al
lows the server to authenticate itself to the client using public-key techniques, then al
lows 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 fol
lows. 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 fol
lowing: 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 be
low. ...
... 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 fol
low 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 al
low 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 al
lowed, 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 fol
lowing 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 fol
lowing 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 al
low 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 be
low: 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 fol
low the fol
lowing 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 fol
lowing 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. fol
lowing 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 al
lowed 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 al
lowed 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 al
lowed. 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 al
low 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 al
lowing 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 fol
lowing 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-overf
low-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-overf
low-style: none; width: 480px; height: 270px; overf
low: 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 fol
lowing 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-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"> al
lowable properties only the fol
lowing 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-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 f
low in a bar pattern. -ms-ring shows animated dots that f
low in a ring pattern. al
lowable properties only the fol
lowing 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. al
lowable properties only the fol
lowing 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 ...
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 fol
lows: 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 al
lows 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 al
lows 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 al
low 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 fol
lowing 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 al
lows 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 fol
lowing code at the beginning of your scripts, al
lowing 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 fol
lowin...
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. be
low 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 fol
lowing 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, fol
lowed 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 fol
lows. error code: 5009 facility code: 10 error message: 'y' is undefined requirements supported in the fol
lowing 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 fol
lowing example illustrates the use of the scriptenginebuildversion function: if(window.scriptenginebuildversion) { console.log(window.scriptenginebuildversion()); } // output: <current build version> requirements supported in the fol
lowing 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 fol
lowing example illustrates the use of the scriptenginemajorversion function: if (window.scriptenginemajorversion) { console.log(window.scriptengine()); } output: <current major version> requirements supported in the fol
lowing 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 fol
lowing example illustrates the use of the scriptengineminorversion function. if (window.scriptengineminorversion) { console.log(window.scriptengineminorversion()); } //output: <current minor version> requirements supported in the fol
lowing 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 fol
lowing 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 fol
lowing 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 fol
lows: 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 fol
lowing 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 fol
lowing 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 fol
lowed 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 fol
lowing 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 fol
lowed 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 fol
lows 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 fol
lowing 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. al
lowing 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 al
lows 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 fol
lowing: 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 fol
lowing constructors: jsexception deprecated constructors optionally let you specify a detail message and other information. method summary the netscape.javascript.jsexception class has the fol
lowing 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, fol
lowing 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 fol
lowing 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 fol
lowing 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 al
low 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 fol
lowed 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 ...
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 be
low 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 fol
lowing 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 be
low). 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 fol
lowing 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 al
lows 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) al
low 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 fol
lowing 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 fol
lowing 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 al
lows 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 fol
lows 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 fol
lowing 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 fol
lowing 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 al
low 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 fol
lowing 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 fol
lowing 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 al
lowing 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 f
low physics simulation of f
lowing 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 bil
lowing 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 fol
low 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 al
lows 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 fol
lowing 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 fol
lowing. 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 fol
lowing 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 be
low 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, be
low 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 be
low 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 be
low, 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, al
lowing 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 be
low, 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 » ...
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 fol
lowing 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 al
lowed in some http headers and in html. the importance of a value is marked by the suffix ';q=' immediately fol
lowed 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 fol
lowing 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, al
low 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 fol
lowing 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 fol
lowing: <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 fol
lowing 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 fol
lows: 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 fol
lows: the code block will continue to run as long as the variable (i) is less than 5. ...
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 al
lows 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 al
low 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 al
low 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 al
lows 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, al
lowing 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 be
low. 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 al
low 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 fol
lowing: 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 fol
lowing 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 fol
lows 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, fol
lowed 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, fol
lowed 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 be
low, 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 be
low. 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 be
low. there are a number of ways that you can achieve this, but i suggest fol
lowing similar patterns as used in the tutorial to do the fol
lowing 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 be
low, 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 fol
lowing live example shows a biography, which has been styled using css. the css properties that i have used are as fol
lows — 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 fol
lowing 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 al
low you to download custom fonts along with your web page, to al
low for more varied, custom text styling. assessments the fol
lowing 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 fol
lowing 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 workf
low. 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 s
lowing 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 al
low users to jump over chunks of your web page. you might want to al
low 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 fol
lowing 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 fol
lowing in the command line to select your project: gcloud config set project gaesamplesite then run the fol
lowing 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 fol
lowing 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 fol
lowers 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 fol
lowing 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 fol
lowing examples, let's assume that the urls are called from within the document located at the fol
lowing 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 fol
low 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 s
low 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 al
lows 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 fol
lowing 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 be
low. 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 be
low. 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: al
lows 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 be
low). 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 be
low 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 fol
low 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 al
lows 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 fel
low 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 fol
lowing 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-fol
low 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, fol
lowing the steps be
low. 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 fol
lowing 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 al
low 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 al
lows 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 al
low 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 al
lowed, the maximum total size of all the assets combined, the minimum al
lowable 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 s
low, 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 s
lowly, 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 fol
low 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 fol
lowing 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 fol
lowing modules. you should start with the first module, then go on to one of the fol
lowing 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 be
low 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 fol
lows best practices that al
low 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 al
low 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 fol
low 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 fol
low 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 fol
lowing 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 al
lowed, 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 al
low 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 fol
lowing 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 fol
lowing 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, al
lowing 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 s
low, 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 ref
low and debugging table ref
low 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 fol
lowing 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 be
low. for complete information, see the build documentation. installing build tools if your system is not listed be
low, 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 fol
lowing 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 fol
lowing, "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 fol
low 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 fol
lowing 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 be
low. 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 fol
lowing 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 fol
low the style guide for the language and module in question. fol
low 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 fol
lowing 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. yel
low 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 al
lowing 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 be
low 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 fol
lowing 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
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 al
lows 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 be
low. to use a postmessage with callback version of chromeworker that features promises, see promiseworker. ...
Chrome-only CSS reference
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 fol
lowing -moz- prefixed xul display values:overf
low-clip-boxthe overf
low-clip-box css property specifies relative to which box the clipping happens when there is an overf
low. it is short hand for the overf
low-clip-box-inline and overf
low-clip-box-block properties.overf
low-clip-box-blockthe overf
low-clip-box-block css property specifies relative to which box the clipping happens when there is an overflo...
...ues:overf
low-clip-boxthe overf
low-clip-box css property specifies relative to which box the clipping happens when there is an overf
low. it is short hand for the overf
low-clip-box-inline and overf
low-clip-box-block properties.overf
low-clip-box-blockthe overf
low-clip-box-block css property specifies relative to which box the clipping happens when there is an overf
low — in the block direction.overf
low-clip-box-inlinethe overf
low-clip-box-inline css property specifies relative to which box the clipping happens when there is an overf
low — 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 fol
lowing doctype: <!doctype html public "-//w3c//dtd html 4.01 transitional//en" "http://www.w3.org/tr/html4/loose.dtd"> the parts are as fol
lows: 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 al
lows 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 fol
lowing: 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 ref
low 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 fol
lowing 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 fol
lowing: 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 fol
lowing 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. fol
lowing 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 fol
lowing 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 fol
lowing 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> f
low diagram the diagram be
low 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.al
low-non-fqdn and network.negotiate-auth.al
low-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 al
lowevents 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 al
lows 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 al
lows 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 fol
lowing 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 al
lows 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 al
lows 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) be
low: 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 al
lowing access to the specified data source. awhattoload a string specifying a uri, or an nsiuri or nsifile object. the returned method will al
low 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 fol
lowing 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 s
low 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 be
low). 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 fol
low 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, al
lows 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 al
lows 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 fol
lowing 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 fol
lowing 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, fol
lowed 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) fol
lowed 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 fol
lowing. 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> be
low 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 fol
lowing 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 al
lows 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, fol
low 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 fol
lowing the web content localizability guidelines. review your code fol
lowing 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 yel
low 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 be
low 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: yel
low" 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 fol
low 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 al
low 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 al
lows you to measure. (at time of writing, linux al
lows 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 fol
lowing 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 s
lowdown. 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 s
lowdown. 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 fol
lowing. 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 fol
lowing. 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 fol
lowing 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 fol
lowing. 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 fol
lowing 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 be
low). "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", "al
lowclipboard"); user_pref("capability.policy.al
lowclipboard.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 al
lows 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 s
lower to use than their uncached counterparts. see monitors for information about uncached monitors. cached monitors functions cached monitors al
low 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 fol
lows. 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 fol
lowing: 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 al
lows 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 fol
lowing 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. fol
lowing 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 fol
lowing 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 fol
lowing 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 fol
lows: 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 f
lowinfo; pripv6addr ip; } ipv6; #endif /* defined(_pr_inet6) */ }; typedef union prnetaddr prnetaddr; fields the structure has the fol
lowing 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. ...
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 fol
lowing 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 al
lows 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 fol
lowing ca certificates were added: none the fol
lowing 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 - al
low preceding text in try comment 1534468 - expose chacha20 primitive 1418944 - quote cc/cxx variables passed to nspr 1543545 - al
low 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 - al
low 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 fol
low-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 - al
low 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 al
low 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 fol
lowing 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 al
low separate virtual servers to have their own session caches. the new approach was to use shared memory for the server session cache, and to al
low 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 fol
lowing 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 b
low 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 shal
low 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 fol
lowing 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 fol
lows: -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
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 fol
lowing 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 fol
lows: -d decode a message. -c encrypt a mes...
... -c content use this detached content (decode only). ...
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 al
lows 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 fol
low 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 be
low 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 fol
lowing // 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 al
lows 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, al
lowing 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 fol
lowing 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 fol
lowing 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 fol
lowing conditions * are met: * * - redistributions of source code must retain the above copyright * notice, this list of conditions and the fol
lowing 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 fol
lowing conditions * are met: * * - redistributions of source code must retain the above copyright * notice, this list of conditions and the fol
lowing disclaimer. * * - redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the fol
lowing 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 s
low because the script being executed must be compiled. constructing a new function object can be s
low 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 fol
lowing 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 fol
lowing 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 al
lowed 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 al
lows 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 fol
low 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 fol
lowing 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 al
lowed 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 al
lowed 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 al
lows 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 be
low), 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 be
low. 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 disal
lowed. 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 overf
low 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 al
lowed 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 fol
lowing 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 fol
lowed 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 al
lowed, 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 al
lowed 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 fol
lowing 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 al
lowed (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 al
lowed (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 disal
lowed (this is *not* the same as saying that a deletion actually occurred -- deleting a non-existent property, or an inherited property, is al
lowed -- 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 al
lows scripts to be loaded from arbitrary cross-origin sources. this al
lows 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 fol
lowing 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 al
lows 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 fol
lowing 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 be
low. 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 "s
low 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 be
low. 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 be
low. 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 be
low. 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 fol
lowing 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 be
low, 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 al
low 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 fol
lowing 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 fol
lows. 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 contentsecuritypolicyal
lows 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 al
lows 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 fol
lowing 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_reportallocationoverf
low(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_reportallocationoverf
low 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_reportallocationoverf
low 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 be
low. 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 be
low. 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 fol
lows. 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 al
low 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 al
lows the runtime to perform garbage collection if needed and al
lows 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 fol
lowed 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 be
low. 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_reportallocationoverf
low 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_reportallocationoverf
low 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 fol
low 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 be
low for that to work, though. step 2 - installing eclipse and setting up the project the fol
lowing 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 fol
lowing 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 fol
lowing 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 fol
lowing content will likely see significant revision, though can be used as a reference for security best practices to fol
low 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 al
low 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 fol
lowing 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" be
low). 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 al
lows 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 fol
low 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 be
low. (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 fol
lows: 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 fol
lowing 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 fol
lowing 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 al
lows 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 fol
lowing 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 fol
lowing 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 be
low: 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 al
lows 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 al
low 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 al
low 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 al
low 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 al
low 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 al
low 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 al
low 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 al
low 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 al
low 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 al
low 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 al
low 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 al
low 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 al
low 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 al
lowed. 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 fol
lowing 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 fol
lowing 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 fol
lowing 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, al
lowing 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 fol
lowing 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 fol
lows: if achannel is an nsihttpchannel and has the 'forceal
lowthirdpartycookie' 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 fol
lows: 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 fol
lowing 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 fol
lowing 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 s
lower, 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 s
lower, 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 al
low 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 fol
lowed 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 aal
lowdelayedload); void removedelayedframescript(in astring aurl); methods loadframescript() loads a script into the remote frame. void loadframescript( in astring aurl, in boolean aal
lowdelayedload ); parameters aurl the url of the script to load into the frame; this must be an absolute url, but data: urls are supported. aal
lowdelayedload 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 al
lowed 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 al
lowed 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 be
low 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 overf
lows 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 al
low 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 al
low 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 be
low.) 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 fol
lowing 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 al
low 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 be
low 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 fol
lowing 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 fol
lowing 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 be
low. 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 be
low, 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. al
lowevents boolean true if the element's al
lowevents 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 al
lowing 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, // outputformatf
lowed = 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, al
lowing 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 al
lows 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 al
lowsuntrusted boolean indicates whether or not the event listener al
lows 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 s
lows 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 fol
lowing 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 window
lowered(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!window
lowered called when a window has been
lowered. void window
lowered( 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 al
lows 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 fol
low 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 al
lowed 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 fol
low 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 be
low. 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 al
lowplugins boolean if true, plugins are al
lowed 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 al
low. 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 fol
lowing 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 fol
lowing 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 fol
lowing properties: nsimsgcompose.compfields, nsimsgcomposeparams.composefields this interface is passed as an argument to the fol
lowing 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); /* al
low duplicate actions in the same filter list? default no. */ attribute boolean al
lowduplicates; /* * 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 fol
lowed 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 al
lows 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 al
lowed 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 be
low 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 al
lows 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 be
low 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: al
low, deny, or unknown (which is the default). see nsipermissionmanager.permission_type_constants for al
lowed 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 fol
lowing 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 al
lows 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 disal
lowed 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 disal
lowed, for example, if it is a http proxy and the nsiprotocolhandler for the queried uri does not permit proxying via http. if a nsiprotocolhandler disal
lows 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 be
low 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 fol
lowing 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 al
low 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 be
low. 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 aal
lowsubstitution ); 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). aal
lowsubstitution when true, al
low 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 al
lows 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 be
low. flag values the aflags parameter is a bit-wise combination of the fol
lowing 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 al
lows 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 fol
lowing 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 al
lows 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 fol
lowing 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 al
lows 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 f
low here is an example of a possible f
low 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 be
low. 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 fol
lowing 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 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 fol
lowing javascript code into the content/ folder next to your myhel
loworld.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 al
lows 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 fol
lowing 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 be
low. 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 fol
lowing places must conform to this format: addon's and target application's version in install and update manifests. the fol
lowing 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 be
low 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 fol
lows: 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 fol
lows: 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 fol
lowing 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 fol
lowing: 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 fol
lowing 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 al
lows 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 fol
lowing: 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 fol
lowing 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 al
lows 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 al
lows 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 al
lows 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 al
lows 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. be
low 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 al
lowed 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 al
lowed 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 be
low 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 yel
low. 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 fol
low 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 be
low 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 be
low. 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 fol
low 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 fol
low 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, fol
lowed 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 shal
low size of that instance. in this case, you can see that the first three arrays have a fairly large shal
low 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. shal
low and retained size this gives rise to a distinction between two ways to look at the size of an object: shal
low 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 shal
low size but a much larger retained size, through the references they contain to other objects. r...
Throttling - Firefox Developer Tools
the network monitor al
lows 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 al
lows 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 be
low 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 fol
lowing 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 be
low. 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 al
lows 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 al
lows 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 al
lows 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 fol
lowing 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 be
low. note: the layout view can be found underneath the layout tab on the right-hand pane of the page inspector. the above and be
low 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 be
low 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 be
low. 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 fol
low 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 be
low 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 ...
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 ref
low: 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 fol
lowing 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 fol
lowing 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 be
low. 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 fol
lowing 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 be
low 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 al
lows 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 al
lows 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 fol
lowing: 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, al
lowing 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 fol
lows: 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 fol
lowing snippet, we aim to download a video using the fetch api. ...
...lue void. examples in the fol
lowing 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}, be
low). this associates the signal and controller with the fetch request and al
lows us to abort it by calling abortcontroller.abort(), as seen be
low 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 fol
lowing snippet, we aim to download a video using the fetch api. ...
... instance. examples in the fol
lowing 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}, be
low). this associates the signal and controller with the fetch request and al
lows us to abort it by calling abortcontroller.abort(), as seen be
low 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 al
lows 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 fol
lowing snippet, we aim to download a video using the fetch api. w...
... streams. examples in the fol
lowing 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}, be
low). this associates the signal and controller with the fetch request and al
lows us to abort it by calling abortcontroller.abort(), as seen be
low 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
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 s
low 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 be
low: 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 fol
lowing 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 fol
lowing 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
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 fol
lowing 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 fol
lows: 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 al
lowed 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 fol
lowing 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 fol
lowing 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 al
lowed. 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 fol
lowing 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 al
lowed. 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 al
low 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
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() al
lows 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() al
lows 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 s
lower 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 fol
lowing 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 be
low 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 fol
lowing 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 fol
lows: 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 fol
lows: > 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 - 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 f
low. ...
...sample payment request: var request = new paymentrequest(supportedinstruments, details, options); // call show() to trigger the browser's payment f
low. 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 f
low 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 f
low. ...
...sample payment request: var request = new paymentrequest(supportedinstruments, details, options); // call show() to trigger the browser's payment f
low. 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 f
low 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 f
low. ...
...sample payment request: var request = new paymentrequest(supportedinstruments, details, options); // call show() to trigger the browser's payment f
low. 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 f
low 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 f
low. ...
...sample payment request: var request = new paymentrequest(supportedinstruments, details, options); // call show() to trigger the browser's payment f
low. 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 f
low 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...
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 al
lows 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 al
lowed 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 fol
lowing 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 be
low 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_al
lowed_err: if the property or declaration block is read only. example the fol
lowing 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 be
low 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 al
low 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
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 al
lowing 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 al
lowed.) 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 fol
lowing 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 yel
lowish 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 s
lower 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 s
lower). 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 be
low. <!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 be
low, 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 al
lows 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 fol
lowing 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 al
lows you to define an area of your canvas and provides another possibility to expose interactive content on a canvas to accessibility tools. it al
lows you to make hit detection easier and lets you route events to dom elements. the api has the fol
lowing 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 be
low). the current values of the fol
lowing 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 fol
lowing transformation methods al
low 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, al
lowing sending of messages from one port and listening out for them arriving at the other. portcollection an array of messageports; an experimental solution to al
low 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 fol
lowing 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" be
low 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
the claim() method of the clients interface al
lows 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 fol
lowing 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
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 al
low) "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 al
low 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
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 fol
lowing 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 al
low 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
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 fol
lowing 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 al
lowed 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 al
lowed to have, and options for interacting with the user. it can contain the fol
lowing 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 fol
lowing 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 fol
lowing 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
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 be
low). 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 al
lowed 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. nomodificational
lowederror 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 al
lowed 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 be
low 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 fol
lows: 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
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 be
low. 2d 3d equivalent a m11 b m12 c m21 d m22 e m41 f m42 methods this interface includes the fol
lowing 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
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 fol
lowing 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
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 al
lows 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 s
low 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
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 fol
lowing 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 fol
lowing polyfill will add the replace method to the domtokenlist class. the fol
lowing 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 be
low. 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 fol
lowing: 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 fol
lowing 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 al
low 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 fol
lowing additional parameters but those parameters are not included in either of the standards listed be
low. 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 fol
lowing 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 be
low. 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 shal
low 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 fol
low 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
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 fol
lowing 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 fol
lowing 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 fol
low 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 fol
low 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 f
low 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 fol
lowing 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 al
low 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 fol
lowing 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 be
low 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
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 be
low 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 fol
lowing 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 (yel
low) 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
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 fol
lowing polyfill will do the job very s
lowly, 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 fol
lowing 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 fol
lowing 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 fol
lows 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 fol
lowing 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 al
lows 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 be
low), 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 fol
lowing exception values: typeerror the typeerror exception may be delivered in any of the fol
lowing 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 al
lowfullscreen 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 be
low. 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 overf
low), 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; overf
low-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.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 fol
lowing 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
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
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 fol
low 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 fol
lows: 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
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 be
low 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 f
low 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 stackoverf
low). 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.al
lowsfeature 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 al
lowed by the feature policy of the current execution context and/or might not be accessible because of user's permissions. featurepolicy.al
lowedfeatures returns a list of names of all features supported by the user agent and al
lowed 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
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 al
lows 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 al
lows 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 al
lows 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 al
lows 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 al
lows 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 al
lowing 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 fol
lowing: 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 fol
lowing: 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 fol
lows: 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 fol
lowing 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 be
low 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
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 be
low.) 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 fol
lowing 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
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 fol
lowing 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 fol
lowing 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
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 fol
lowing 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 fol
lowing 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
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
(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 al
lowing 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 al
lowing 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 al
lowing 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 fol
lowing performanceentry properties (for "frame" performance entry types) by qualifying and constrainting the properties as fol
lows: 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 al
low 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
(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 al
lowed 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
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 fol
lowing 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 al
lowed 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 al
low 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 be
low to make into a box that resizes and changes color and such. <div class="box"></div> css the css be
low 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 al
low 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 al
low */ 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 fol
lowing 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 fol
lowing: 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 fol
lowing 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 al
low 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 f
low 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 fol
lowing properties are now obsolete: alink, bgcolor, background, link, text, and vlink. the fol
lowing 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 fol
lowing properties have been added: disabled, elements, name, type, valdiationmessage, validity, and willvalidate. the fol
lowing 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 fol
lowing a preorder, depth-first traversal of the tree. this is called tree order. the elements included by htmlformelement.elements and htmlformelement.length are the fol
lowing: <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 fol
lowing 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 fol
lowing 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 fol
lowing 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 be
low. 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 be
low 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: f
low-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 fol
lowing 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 ref
low 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 ref
low 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 ref
lows. example the addimagetolist() function shown be
low 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 f
lowchart. the longdesc property could be used to provide an explanation of the f
low 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 f
low 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 fol
lowing 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 al
lows 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 fol
lowed 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 al
lowed, 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 fol
lowing 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 fol
lowing 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 fol
lowing properties: crossorigin, referrerpolicy, and as. html 5.1the definition of 'htmllinkelement' in that specification. recommendation html5the definition of 'htmllinkelement' in that specification. recommendation the fol
lowing properties are now obsolete: charset, rev, and shape. the fol
lowing 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.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 be
low 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 be
low 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 fol
lowing 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.rangeunderf
low) { input.setcustomvalidity('we need a higher number!'); input.reportvalidity(); } else if (input.rangeoverf
low) { 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 fol
lowing properties are now obsolete: align, archive, border, code, codebase, codetype, declare, hspace, standby, and vspace. the fol
lowing properties have been added: typemustmatch, contentwindow, willvalidate, validity, and validationmessage. the fol
lowing 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 be
low. 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 al
lowed 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 fol
lowed by a 'w' with the width of the images, or an 'x' fol
lowed 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 fol
lowing 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
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 al
lows 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 fol
lowing 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 al
lowed", 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 fol
lowing 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 al
lows 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 fol
lowing 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
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 fol
lowing 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 al
lows 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
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 fol
lowing 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 be
low 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 fol
lowing 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 fol
lowing 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 al
lowed on an object. unless the cause of the error is corrected, retrying the same operation would result in failure. not_al
lowed_err 6 an operation was called on an object where it is not al
lowed or at a time when it is not al
lowed. 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
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 be
low 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 fol
lowing 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
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 fol
lowing 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 fol
lowing 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 fol
lowing line, you should include the prefixes // of implementations you want to test. window.indexeddb = window.indexeddb || window.mozindexeddb || window...
IDBIndex.count() - Web APIs
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 fol
lowing 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 fol
lowing 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
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 fol
lowing 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 fol
lowing 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
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 fol
lowing 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 fol
lowing 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
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 al
low 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 fol
lowing 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
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 fol
lowing types: exception description dataerror the value parameter passed was not a valid key. example the fol
lowing 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
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 fol
lowing 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 fol
lowing type: exception description dataerror the value parameter passed was not a valid key. example the fol
lowing 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 fol
lowing two values: value meaning pending the request is pending. done the request is done. example the fol
lowing 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. fol
lowing 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 be
low. 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 fol
lowing code is taken from chrome's grab frame - take photo sample. since imagecapture requires some place to capture an image from, the example be
low 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, fol
lowing 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 fol
lowing 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
-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:yel
low;} [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 '/' fol
lowed by the path of the url. location.search is a usvstring containing a '?' fol
lowed 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 '#' fol
lowed 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 fol
lowing 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 fol
lows: 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 fol
lows: 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 al
lows 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 fol
lowing 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, fol
lowed by a stop event. note: if the browser is unable to start recording or continue recording, it will raise a domerror event, fol
lowed by a mediarecorder.dataavailable event containing the blob it has gathered, fol
lowed 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 disal
low 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 al
lowed 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 fol
lowing: 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 be
low 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 al
low that type of action to be performed. the fol
lowing 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 be
low 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 al
low that type of action to be performed. the fol
lowing 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 f
lowing 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 fol
lowing 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 f
lowing 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 fol
lowing 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. be
low 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 be
low 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 al
low 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; fol
lowing 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 fol
lowing 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 fol
lowing 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 al
lows 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 fol
lowing 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 fol
lowing 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 al
lowed 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 al
lowed 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 al
lows 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 al
lows 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 fol
lowing 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
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 fol
lowing 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 f
low 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 fol
lowing 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 fol
lowing 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
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 al
low 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 be
low. .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 be
low). 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 fol
lowing 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 fol
lows 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 be
low. 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 fol
lowing 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 fol
lowing: 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 al
low use of this feature in insecure contexts. notal
lowederror note: no user agent currently throws this exception, but the specification describes the fol
lowing behaviors: this document is not al
lowed to use this feature. for example, it might not be explicitly al
lowed 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+ al
lows users to set the browser identification string via a menu. microsoft internet explorer uses the windows registry. safari and icab al
low 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 fol
lows 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 fol
low-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 fol
lowing 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 fol
lowing 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 's
low-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 fol
lowing 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 === 's
low-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 fol
lowing values: name value document_position_disconnected 1 document_position_preceding 2 document_position_fol
lowing 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_fol
lowing) { 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
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
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
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, al
lowing 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, al
lowing 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 al
lowing 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 al
lowed 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 al
lows 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 al
lowed 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 al
lows 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 al
lowed 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 fol
lowing: 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 be
low 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 be
low. examples basic example the fol
lowing 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 fol
lowing three examples go together to show creating, loading, and using a paintworklet. create a paintworklet the fol
lowing 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 fol
lows (negative values are not al
lowed): "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 s
lower 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
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 al
lowing 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 fol
lowing 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 be
low 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 fol
lowing 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 be
low 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 al
lows 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. al
lows 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 al
lowed 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 al
lowed 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 fol
lowing 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 fol
lowing 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
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 be
low. 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 fol
lowing 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 be
low. 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 al
low 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 fol
lowing 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-al
low-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
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 be
low) 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 al
lows 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 be
low) 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 al
lows 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 fol
lowing 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 fol
lowing 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 fol
lowing 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.al
lowcredentials 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 be
low 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 al
lows 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 al
low 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 fol
lowing 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, al
lowing 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 be
low the value specified in the bufferedamount
lowthreshold property, the user agent fires the bufferedamount
low 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 fol
lows: 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 fol
lowing 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 be
low 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 be
low, 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 fol
lowing 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 fol
lowing 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 be
low. obsolete properties the fol
lowing 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 f
low 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 be
low 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 be
low 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 fol
lowing 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 f
low 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 al
low it to re-synchronize with the media. however, the primary purpose of a pli packet is to al
low 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 be
low 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 be
low 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 be
low 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 al
lowing 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 be
low, 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 fol
lowing 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 be
low, 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 f
low 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 fol
low 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 be
low 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 fol
lowed 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 al
low 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 be
low 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 be
low 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 be
low. 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 fol
lowing 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 fol
lowing: 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 al
lowing 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 fol
lowing 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
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 fol
lowed if the request's redirect property is "fol
low" 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 al
low 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
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 fol
lowing 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('f
lowers.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 fol
lowing 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('f
lowers.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 al
lowing 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 al
lowing 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 fol
lowing 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 fol
lows 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-al
low-origin http response header with a value specifying the origin or origins which are al
lowed 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
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
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('f
lowers.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 fol
lowed, 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 be
low, 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 fol
lowing 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 fol
lowing 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 al
lowed 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 fol
low 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_al
lowed_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 be
low. 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 fol
lowing 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 be
low. 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 fol
lowing 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 al
lows 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
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 fol
lowing 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 be
low 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 al
low 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 fol
lowing 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 al
lows configuring the notification. it can have the fol
lowing 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 fol
lowing 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 al
lows 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 fol
lowing 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 al
lows 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 al
lows 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 — al
lows 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-al
lowed the user agent disal
lowed any speech input from occurring for reasons of security, privacy or user preference. service-not-al
lowed the user agent disal
lowed 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 al
low 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-al
lowed the user agent disal
lowed any speech input from occurring for reasons of security, privacy or user preference. service-not-al
lowed the user agent disal
lowed 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 al
low another more suitable speech recognition service to be used instead. bad-grammar ...
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 be
low 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
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 fol
lowing function iterates over the local storage keys: function foreachkey(callback) { for (var i = 0; i < localstorage.length; i++) { callback(localstorage.key(i)); } } the fol
lowing 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 al
low 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 al
low-storage-access-by-user-activation sandbox token to al
low storage access requests to be successful, along with al
low-scripts and al
low-same-origin to al
low it to call the api, and execute in an origin that can have cookies: <iframe sandbox="al
low-storage-access-by-user-activation al
low-scripts al
low-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() fol
lowed 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 fol
lowing 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 fol
lowing: 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 fol
lowing 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 fol
lowing: 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 fol
lowing 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 fol
lowing: 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 fol
lowing 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 fol
lowing: 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 fol
lowing 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
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 al
lows 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 al
lows to specify any text node and obtain all adjacent text as a single string. ...
Text - Web APIs
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 fol
lowing 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 baselinesbe
lowalphabetic = ['ideographicbaseline', 'emheightdescent', 'actualboundingboxdescent', 'fontboundingboxdescent']; const baselines = [...baselinesabovealphabetic, ...baselinesbe
lowalphabetic]; 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 (baselinesbe
lowalphabetic.includes(baseline)) { liney = y + ...
Touch() - Web APIs
"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 al
lowed 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 fol
lowing 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 be
low 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. be
low 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 al
low 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 be
low 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
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 al
low 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 al
low 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 fol
lowing 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 fol
lowing 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 be
low. dfactor a glenum specifying a multiplier for the destination blending factors. the default value is gl.zero. for possible values, see be
low. ...
... 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 fol
lowing 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 al
lowed 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 be
low for possible values. param a glint specifying a value to set the pname parameter to. see be
low for possible values. return value none. pixel storage parameters parameter name (for pname) description type default value al
lowed 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 fol
lowing values are available additionally: constant description type default value al
lowed 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 fol
lowing 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 be
low) 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 fol
lowing objects can be used...
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 al
lows 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 al
lows 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 al
low 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 fol
lowing 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 al
lows 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 fol
lowing 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 be
low. 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
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 fol
lowing 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 fol
lows cross-domain rules; that is, you can only load textures from sites for which your content has cors approval. see cross-domain textures be
low 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 al
low 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 al
lowed, 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
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 be
low, 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 be
low 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 fol
low 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, al
lowing 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 fol
low 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 al
low 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 al
lowed 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 al
low 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 be
low 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 be
low 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 be
low. 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 al
lowed 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 fol
lowing 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 be
low. ...
...mple be
low. 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 al
low 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 be
low 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 be
low 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 be
low 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
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 fol
lowing 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 fol
lowing 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
the window.statusbar property returns the statusbar object, whose visibility can be toggled in the window. syntax objref = window.statusbar example the fol
lowing 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
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 fol
lowing 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 fol
lowing 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 workf
low please note that the unload event also fol
lows the document tree: parent frame unload will happen before child frame unload (see example be
low). 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> be
low, 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 fol
lowing 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 be
low }, [ 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 al
lows 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 fol
lowing 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() al
lows 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 fol
lowing 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 al
lows 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 fol
lowing 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 be
low 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 fol
lowing 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 be
low. "" 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 al
lowed 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 fol
lowing: "" 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 al
lowed 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 be
low. 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 al
lows 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 fol
lowing example shows the use of the evaluate() method. html <div>xpath example</div> <div>number of <div>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 al
lows 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 fol
lowing example shows the use of the evaluate() method. html <div>xpath example</div> <div>number of <div>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 al
lowed to move. this is typically used when the xr system is capable of tracking the user's physical movement within a limited distance of their starting position. the specified bounds may, in fact, describe the shape and size of the room the user is located in, in order to let the webxr site or application prevent the user from colliding with the walls or other obstacles in the real world. at a minimum, the boundaries indicate the 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 fol
lowing: 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 al
lowing 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 al
low 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 al
low the use of iterators and the foreach() method is also available. properties the fol
lowing properties are available on xrinputsourcearray objects. length read only the number of xrinputsource objects in the list. methods the fol
lowing 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 be
low 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 be
low. 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 be
low 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 be
low 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 be
low, 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 al
lows 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 be
low, 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 al
lows 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 fol
lowing 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 be
low 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 be
low, 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 al
lows 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 be
low 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 al
low 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 fol
lowing: 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 al
lowing 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 be
low 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 be
low, 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 al
lows 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 al
lowing 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 al
low 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 fol
lowing example uses addeventlistener() to establish handlers for the selection events: selectstart, selectend, and select. this snippet is the core of an event handler to al
low 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, al
lowing 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 be
low 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 fol
lowing example uses addeventlistener() to establish handlers for the selection events: selectstart, selectend, and select. this snippet is the core of an event handler to al
low 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, al
lowing 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 be
low 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 fol
lowing example uses addeventlistener() to establish handlers for the squeezeion events: squeezestart, squeezeend, and squeeze. this snippet is the core of an event handler to al
low 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, al
lowing 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 be
low 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 fol
lowing example uses addeventlistener() to establish handlers for the squeezeion events: squeezestart, squeezeend, and squeeze. this snippet is the core of an event handler to al
low 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, al
lowing 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 be
low dispatch the action out to a specialized function to handle things. after checking to ens...
XRSystem - Web APIs
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 fol
lowing 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 fol
lowing 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
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 al
low 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 fol
lowing 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 be
low: 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 al
low the same style to be reused for multiple content, as well as simplify maintenance and al
low 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 al
low 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 al
lows xslt to add, remove and reorganize elements from the original xml document and thus al
lows 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 fol
lowing: 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 be
low 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 be
low 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 be
low 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 fol
lowing: 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 al
lowing 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 fol
lowing: 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 be
low 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 fol
lowing: 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 be
low 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 be
low 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-f
lowto aria-labelledby aria-owns aria-posinset aria-rowcount aria-rowindex aria-rowspan aria-setsize microsoftedge-specific properties x-ms-aria-f
lowfrom ...
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 al
lows 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 al
low 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, al
lowing 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 al
low 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, al
lowing 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 al
low 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, al
lowing 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 al
lows an assistive technology user to quickly bypass large sections of repeated content (main navigation, info banners, etc.). this al
lows the user to access the main content of the page faster. adding an id attribute to the element with a declaration of role="main" al
lows 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, al
lowing 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 fol
lowing 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 fol
lowing 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 al
low 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, al
lowing 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 al
low 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, al
lowing 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 fol
lowing: 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 fol
lowing 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 fol
lowed 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 al
lows 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 al
lows 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 fol
lowing 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" fol
lowed 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 fol
lowing 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 g
low 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 fol
lowing table describes tabindex behavior in modern browsers: tabindex attribute focusable with mouse or javascript via element.focus() tab navigable not present fol
lows the platform convention of the element (yes for form controls, links, etc.). fol
lows 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 be
low 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" be
low. 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 be
low 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 fol
lowing progress meter is horizontal (the default): </p> <progress max="100" value="75"></progress> <p> the fol
lowing 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: be
low; -webkit-box-reflect: left; -webkit-box-reflect: right; /* offset value */ -webkit-box-reflect: be
low 10px; /* mask value */ -webkit-box-reflect: be
low 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, be
low, 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, be
low, 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 "g
low" (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-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 fol
lowing 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 be
low 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 be
low 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
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 fol
lowed 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 al
lows 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: yel
low; 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 al
lowed 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 al
lows 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; } al
lowable 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 be
low) */ ::-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
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 al
lows 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
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 fol
lowing 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 fol
lowing rules: // give the two elements distinctive backgrounds p { background: yel
low; } simple-custom { background: cyan; } // both the custom and the built-in element are given italic text :defined { font-style: italic; } then provide the fol
lowing 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
), 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
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 fol
lowing methods in the fol
lowing 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, fol
lowing 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 al
lowing 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 be
low @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, fol
lowed 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 fol
lowing 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 fol
lowing 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 al
low 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: yel
low; } } 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 fol
lowing 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 fol
lowing 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 be
low. 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 yel
low 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 yel
low 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: yel
low; } } @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 be
low. ...
... 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 fol
lowed 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 (fol
lowed) 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: yel
low } 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 fol
lowing 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 al
lows 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 fol
lowed by one of the keywords defined in the css specification, such as auto or pointer. for example, the fol
lowing value would be al
lowed: 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 be
low 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 al
lows 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 ...
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 be
low 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 be
low 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 overf
lowing the parent. both horizontal and vertical alignment of the children can be easily manipulated. basic example in the fol
lowing 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-f
low 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-f
low: 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 fol
lowing 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 be
low 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-f
low 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 overf
low overf
low 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 be
low. 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 fol
lows the first (though not necessarily immediately), and both share the same parent. syntax: a ~ b example: p ~ span will match all <span> elements that fol
low a <p>, immediately or not. adjacent sibling combinator the + combinator selects adjacent siblings. this means that the second element directly fol
lows 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 fol
low a <p>, immediately or not. adjacent sibling combinator the + combinator selects adjacent siblings. this means that the second element directly fol
lows the first, and both share the same parent. syntax: a + b example: h2 + p will match all <p> elements that directly fol
low 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 al
low 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 be
low 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
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 fol
lowed 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 al
lows 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
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 al
lowed 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 be
low 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 fol
lows 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 fol
lowing: 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 be
low. 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 al
low 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 al
lowing 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 fol
lowing 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 fol
lowing: <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 fol
low 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 fol
lowing 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 be
low. 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 al
low 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 al
low 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 al
lows 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 al
lowed 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 al
low 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 al
lowing 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 fol
lows: each layer may include zero or one occurrences of any of the fol
lowing 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 fol
lowing example, we have a <div> with two background images set on it — a firefox logo on top of a linear gradient. be
low it we have a provided a <select> menu that al
lows you to change the background-blend-mode applied to the <div>, al
lowing 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: yel
low; 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: yel
low; 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: yel
low; 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: yel
low; 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 fol
lowing css properties: border-block-color border-block-style border-block-width syntax values the border-block is specified with one or more of the fol
lowing, 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 be
low. 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 fo
lowing example shows a simple <div> with a border image set on it. the source image for the borders is as fol
lows: 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 fol
lows: 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 al
low you to dynamically change the values of the above two properties, al
lowing 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 be
low. 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 be
low. 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: yel
low; 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: yel
low; 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 fol
lowing 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 be
low. 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, yel
low, green); box-shadow: 8px 8px 10px 0px deeppink, -5px -5px 5px 0px blue, 5px 5px 15px 0px yel
low; 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 overf
low 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 be
low 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 be
low 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 f
lowed 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 al
low 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
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 fol
lowing: a <custom-ident> naming the counter, fol
lowed 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 fol
lowing: a <custom-ident> naming the counter, fol
lowed 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 fol
lowing: a <custom-ident> naming the counter, fol
lowed 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
<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
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 f
low 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 fol
lows 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 f
lowed with surrounding content as if it were a single inline box (behaving much like a replaced element would). it is equivalent to inline f
low-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 be
low 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
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="overf
low:hidden; height:0;"> <div id="mybackground1" style="width:1024px; height:1024px; background-image: linear-gradient(to right, red, orange, yel
low, 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="overf
low: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 al
low you to choose between the different types of filter function, and a slider to al
low you to vary the values used inside the filter function. updating the controls updates the filter effect in real time, al
lowing 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-f
low 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 - al
low 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 fol
lowing 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 al
lows 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 be
low, 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 fol
low 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, al
lowing 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 al
lows 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
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 al
lowed between the number and the unit. 0 although unitless zero is an al
lowable <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
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 be
low. 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, yel
low, 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, yel
low, 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
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 fol
lowing 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
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, al
lowing 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, al
lowing 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
the <image> css data type represents a two-dimensional image. syntax the <image> data type can be represented with any of the fol
lowing: 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 fol
lowing 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 fol
lowing 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 al
lowed by this type. examples length-percentage examples the fol
lowing 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 al
lowable type, this means that the percentage resolves to a length and therefore can be used in a calc() expression. therefore, all of the fol
lowing 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 fol
lowing: 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 fol
lowing 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 be
low in the fol
lowing 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 fol
lowing 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 fol
lowing 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
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 be
low, 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 al
low the new styles to take effect. ...
...d be
low, 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 al
low 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 fol
lows: 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 al
lowed 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
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 fol
lowed by at least one digit. +-12.2 only one leading +/- is al
lowed. 12.1.1 only one decimal point is al
lowed. 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 al
lows 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 /* fol
low the path direction, with optional additional angle */ offset-rotate: auto; offset-rotate: auto 45deg; /* fol
low 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 fol
lowed 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 be
low. 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 be
low. 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 g
low. 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
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 fol
lowing 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 be
low. 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 fol
lowing 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 fol
lowing 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: yel
low; 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: yel
low; 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 fol
lows: page-break-inside break-inside auto auto avoid avoid formal definition initial valueautoapplies toblock-level elements in the normal f
low 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 al
lows 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 al
lows 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 be
low. 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 al
low 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 al
lowed 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 al
lows 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, fol
lowed 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 fol
lows 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 al
lows 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 al
lows 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 al
lows 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 al
lowed. 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; overf
low: 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 al
lowed. 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; overf
low-x: hidden; overf
low-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 be
low. 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 be
low 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 fol
lowing 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 fol
lowing 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 hol
low. 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 be
low. 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 be
low 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
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 be
low 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 be
low 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 al
lows 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 al
lows the display of data that is already formatted using a tool fol
lowing 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
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 fol
lowing 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 be
low. 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 al
lows 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). overf
low uievent mozilla specific an element has been overf
lowed by its content or has been rendered for the first time in this state (only works for elements styled with overf
low != 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 underf
low uievent mozilla specific an element is no longer overf
lowed by its content (only works for elements styled with overf
low != 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 fol
lows along the ground plane, perpendicular to the y axis and positive toward the east (and therefore negative toward the west). the y axis fol
lows 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>. f
low content elements belonging to the f
low 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 f
low 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
xhtml is a term that was historically used to describe html documents written to conform with xml syntax rules. the fol
lowing 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 s
low 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 fol
low 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 ⁦ 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 ⁨ 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 ‪ dir="ltr" sets the base direction to ltr but al
lows 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 ‫ 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 ‭ <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 fol
lowing 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 fol
lowing <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 al
lows (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 al
lowed 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
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 al
lowed (barring other constraints, such as min and max). the default stepping value for number inputs is 1, al
lowing 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 al
low 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 f
low 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 f
low 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 fol
lowing 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 fol
lowing 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
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 f
low content, palpable content. permitted content f
low 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 f
low 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 f
low 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
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 f
low content, sectioning content, palpable content. permitted content f
low content. tag omission none, both the starting and ending tag are mandatory. permitted parents any element that accepts f
low 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 f
low. 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
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 fol
lowing 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 al
lowed. 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 f
low content, sectioning root, palpable content. permitted content f
low content. tag omission none, both the starting and ending tag are mandatory. permitted parents any element that accepts f
low 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 ...
<br>: The Line Break element - HTML: Hypertext Markup Language
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 fol
lowing 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 f
low 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
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 f
low 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
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> al
lows 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 fol
lowing attributes are deprecated and should not be used. they are documented be
low 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
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 fol
lowed 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 fol
lowing attributes are deprecated and should not be used. they are documented be
low 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
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 f
low content. tag omission none, both the starting and ending tag are mandatory. permitted parent elements any element that accepts f
low 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 fol
lowing. 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
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 f
low 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 fol
lowing 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
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 f
low 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; overf
low: 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
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 fol
lowing: 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 f
low content, sectioning root, interactive content, palpable content. permitted content one <summary> element fol
lowed by f
low content. tag omission none, both the starting and ending tag are mandatory. permitted parents any element that accepts f
low content. implicit aria role group permitted aria roles no role permitted dom interfa...
<div>: The Content Division element - HTML: Hypertext Markup Language
the html content division element (<div>) is the generic container for f
low 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 f
low content, palpable content. permitted content f
low 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 f
low content, palpable content. permitted content f
low content. or (in whatwg html): if the parent is a <dl> element: one or more <dt> elements fol
lowed 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 f
low 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
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 fol
lowed 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 f
low 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 fol
lowed 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
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 f
low 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>f
low</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
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 f
low 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 al
lowed. 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 al
lowed. 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
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, al
lowing you to make the <fieldset> part of that <form> even if it is not nested inside it, and disabled, which al
lows 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 f
low content, sectioning root, listed, form-associated element, palpable content. permitted content an optional <legend> element, fol
lowed by f
low content. tag omission none, both the starting and ending tag are mandatory. permitted parents any element that accepts f
low content. implicit aria role group permitted aria roles radiogroup, presen...
<header> - HTML: Hypertext Markup Language
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 f
low content, palpable content. permitted content f
low 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 f
low 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 al
lowed <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
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 fol
lowing 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, al
lowing 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
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 f
low 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; overf
low: 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
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 f
low content, palpable content. permitted content f
low content. tag omission none; both the starting and ending tags are mandatory. permitted parents where f
low 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 al
lows 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
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 f
low 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 fol
lowing 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
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 f
low 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; overf
low: 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
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 al
lowed 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 al
low 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
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 f
low 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 '#' fol
lowed 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
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 fol
lowing 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
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” be
low. the source for this interactive example is stored in a github repository. if 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 f
low 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 f
low 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 fol
lowed 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 f
low content. ...
<progress>: The Progress Indicator element - HTML: Hypertext Markup Language
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 f
low 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 al
lowed 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
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 f
low 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; overf
low: 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
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 f
low 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 al
low 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
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 f
low 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 fol
lowed by "w", such as 300w. the default value, if missing, is the infinity. a pixel density descriptor, that is a positive floating number directly fol
lowed 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
> 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 f
low content. tag omission the start tag is mandatory. the end tag may be omitted, if it is immediately fol
lowed 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 be
low 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
stored in a github repository. if 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 fol
lowed 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
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 f
low 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 be
low. 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
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 f
low 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 be
low, 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 al
low 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 fol
lowing the production rule of xml names with the fol
lowing 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 fol
lowing 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 al
low 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 fol
lowing 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 al
low 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 fol
low 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 fol
lowed 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 fol
lowed 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 fol
lowed 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 fol
lowing 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 fol
lowing content-security-policy violation occurred on " . $current_domain . ":\n\n" . $json_data . "\n\nfurther cps violations will be logged to the fol
lowing 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 al
lows 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> 'al
low-duplicates'; <domstring> any string can be a trusted type policy name. 'al
low-duplicates' al
lows 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 al
lows 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 al
lows 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 al
lows 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-al
low-popups | same-origin directives unsafe-none this is the default value. al
lows 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-al
low-popups. same-origin-al
low-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 al
lows 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 fol
lowing 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 al
low 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
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 fol
lowed. 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, s
low 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 al
lows 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 al
lows 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-al
low-origin header to specify the domains that are al
lowed 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, al
lowing access via http. preloading strict transport security google maintains an hsts preload service. by fol
lowing 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 fol
lowing 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
the trailer response header al
lows 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 al
low 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 al
low 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 disal
lowed: 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 al
lows 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
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 al
low a uniform method to cover the fol
lowing 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
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 be
low, 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 be
low, 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 al
lows 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 fol
lowing object keys can be specified in the nel header: report_to the reporting api group to send network error reports to (see be
low). 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
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 be
low) 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 disal
lows 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 be
low which are available. some sample code fol
lows 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://stackoverf
low.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 al
low 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 be
low 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 be
low). 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 fol
lowed by an "o", // u? optionally fol
lowed by a "u" // r fol
lowed 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 f
low, 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 al
lows parallel computation. websockets al
lows
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, al
lowing 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 world" 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 fol
lowing 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 be
low. 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 al
low . 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 fol
lowing 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 al
lowed 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 fol
lowed by a
lowercase or uppercase latin letter "o" (0o or 0o). examples "0"-prefixed ...
...o fol
lowed 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 fol
lowed 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 fol
lowing 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 fol
lowing function: function car(make, model, year) { this.make = make; this.model = model; this.year = year; } now you can create an object called mycar as fol
lows: 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 al
lowed range for these methods is usually between 0 and 20 (or 21). however, the ecmascript specification al
lows 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 fol
lows: 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 fol
lows: 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] be
low... 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] be
low, 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 fol
lowing code at the beginning of your scripts. this will al
low 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 al
lows 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 s
lower 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 fol
lowing 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 be
low. 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 fol
lowing 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) fol
lowed 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 be
low 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 stackoverf
low 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 al
lowing 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 fol
lowing 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 fol
lowing 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 al
lowed by the specification. most notably, the ie and edge browsers insert bidirectional control characters around dates, so the output text will f
low 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 fol
lowing 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 al
lowed value for the type option. examples using format the fol
lowing 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 fol
lowing 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 fol
lowing 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 be
low. 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 al
lows 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 fol
lowing: 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 al
lows 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 fol
lowing 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 al
lows 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 fol
lowing 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 fol
lowing 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 fol
low 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 al
low trailing commas // both will throw a syntaxerror json.parse('[1, 2, 3, 4, ]'); json.parse('{"foo" : 1, }'); json.parse() does not al
low 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 s
lower, 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 fol
lowing values: for the built-in object object, tosource() returns the fol
lowing 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 fol
lowing 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 fol
lows: 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" be
low. 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 fol
lowing 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 ps
low = new promise((resolve, reject) => { settimeout(resolve, 500, "done eventually"); }); const pfast = new promise((resolve, reject) => { settimeout(resolve, 100, "done quick"); }); promise.any([perr, ps
low, 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 be
low 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 disal
low 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() al
lows 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 al
low 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 fol
lowing 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 fol
lowing the most recent match. examples using lastindex consider the fol
lowing 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 be
low 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 fol
lowing 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 fol
lowing 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'.to
lowercase()) // 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 fol
lowing 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 al
low 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 al
lows 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 al
lowed. 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 al
lows 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 al
lows 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 al
lows 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 fol
lowing 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. ...
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 al
lows you to execute a map() function on each element of the typed array (or subclass object) that is being created. this means that the fol
lowing 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 fol
lowing code at the beginning of your scripts, al
lowing 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 shal
low 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 be
low. on the fol
lowing 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 fol
lowing 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 fol
lowing 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.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 al
lows 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 fol
lowing 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 fol
lowing 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 al
lowed 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 al
lowed 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 fol
lowing 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 fol
lowing 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 fol
lowing: 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 fol
lowing 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 al
lows 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 fol
lowing 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 fol
lowing code uses the comma operator to increment i and decrement j at once. the fol
lowing 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 fol
lowing 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 fol
lows: 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 fol
lows: 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 al
lowed. 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 fol
lowing syntax is often seen in many scripts. x = eval('document.forms.form_name.elements.' + strformcontrol + '.value') eval() is s
low 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 al
low 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 al
lowed typeof foo; // returns "function" typeof class {}; // returns "function" foo instanceof object; // true foo instanceof function; // true class foo {} // throws syntaxerror (class declarations do not al
low 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 al
lowed 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 fol
lowing 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 fol
lowing 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 al
lows 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 al
lows 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 al
lows 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 fol
lowing 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 al
lows 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 fol
lowing 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 be
low 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 al
lowed 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 f
low 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 fol
lowing 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, fol
lowed 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 al
low "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 be
low 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 fol
lowing 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 fol
lowing 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
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
, 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
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 be
low 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
, 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 fol
lowing: 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 fol
lowing: 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 al
low 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
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 al
lows 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 al
lows 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 al
lows 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 fol
lowing 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
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 fol
lowing consecutive characters: "space" (u+0020), "tab" (u+0009), "line feed" (u+000a), "carriage return" (u+000d), and "form-feed" (u+000c). the fol
lowing 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 fol
lowing 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
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 fol
lowing the fol
lowing 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 fol
lowing 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 fol
lowing 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 al
lowed 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
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 fol
lowing 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 al
lows 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 be
low 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 fol
lowing 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
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 fol
lowing 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 al
lows 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 fol
lowing 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 fol
lowing 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 (fol
lowed 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 al
lows 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
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 al
low 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 fol
lowing 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 fol
lowing 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
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 fol
lowing 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 f
low 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 f
low direction. both the writing mode and the typographic mode are horizontal. vertical-rl this value defines a right-to-left block f
low direction. both the writing mode and the typographic mode are vertical. vertical-lr this value defines a left-to-right block f
low 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 al
lowing animations to control translation, scaling, rotation, and/or skewing. ...
... the animatetransform element animates a transformation attribute on its target element, thereby al
lowing animations to control translation, scaling, rotation, and/or skewing. ...
<discard> - SVG: Scalable Vector Graphics
the <discard> svg element al
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. ...
...
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
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-f
lowto, 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, be
low 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 fol
lowing 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 al
lows 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 fol
lows: 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 fol
lows: 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
the <femerge> svg element al
lows 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 al
lows 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-f
lowto, 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
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-f
lowto, 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 fol
lowing 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
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 fol
lowing 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
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-f
lowto, 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
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-f
lowto, 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 fol
lowing 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
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 fol
lowing 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="yel
low" 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
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-f
lowto, 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
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-f
lowto, 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
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-f
lowto, 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
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-f
lowto, 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...
<set> - SVG: Scalable Vector Graphics
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 al
lowed, 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
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-f
lowto, 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 fol
lowing 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
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-f
lowto, 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
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-f
lowto, 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 al
low 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 al
low 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 al
lowed, 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 be
low. 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="yel
low" 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 al
low 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 s
low. 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 fol
lows 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
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 be
low. 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 fol
lowed, 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 fol
lowing 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 fol
lowing 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 fol
lowing 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 al
lowed 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 al
lows 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 al
low 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 al
low 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 al
lows 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
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 fol
lowing 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. fol
lowing indicates all the nodes that appear after the context node, except any descendant, attribute, and namespace nodes. fol
lowing-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
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 al
lowable 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 al
lowable 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
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 fol
lows: <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 fol
lowing: <img src="/images/mygraphic.jpg"/> the element annotations that fol
low 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 fol
lowing fol
lowing-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 fol
lowing fol
lowing-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 fol
lowing 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
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 al
lows 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 al
lows 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 al
low 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 be
low 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, al
lowing 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 al
low 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...