Search completed in 1.02 seconds.
2617 results for "before":
Your results are loading. Please wait...
::before (:before) - CSS: Cascading Style Sheets
Web › CSS › ::before
in css, ::before creates a pseudo-element that is the first child of the selected element. it is often used to add cosmetic content to an element with the content property. it is inline by default. /* add a heart before links */ a::before { content: "♥"; } note: the pseudo-elements generated by ::before and ::after are contained by the element's formatting box, and thus don't apply to replaced elements such as <img>, or to <br> elements. syntax /* css3 syntax */ ::before /* css2 syntax */ :before note: css3 introduced the ::before notation (with two colons) to distinguish pseudo-classes from pseudo-elements. browsers also accept :before, introduced in css2. examples adding quotation marks one simple example of using ::before pseudo-elements is to provide quotation marks. here w...
...as <img>, or to <br> elements. syntax /* css3 syntax */ ::before /* css2 syntax */ :before note: css3 introduced the ::before notation (with two colons) to distinguish pseudo-classes from pseudo-elements. browsers also accept :before, introduced in css2. examples adding quotation marks one simple example of using ::before pseudo-elements is to provide quotation marks. here we use both ::before and ::after to insert quotation characters. html <q>some quotes,</q> he said, <q>are better than none.</q> css q::before { content: "«"; color: blue; } q::after { content: "»"; color: red; } result decorative example we can style text or images in the content property almost any way we want. html <span class="ribbon">notice where the orange box is.</span> css .ribbon { b...
...this method can often be used to add small touches to the ui and improve user experience. ...
...And 3 more matches
break-before - CSS: Cascading Style Sheets
the break-before css property sets how page, column, or region breaks should behave before a generated box. if there is no generated box, the property is ignored. ...
... the break-before css property sets how page, column, or region breaks should behave before a generated box. if there is no generated box, the property is ignored. ...
... the break-before css property sets how page, column, or region breaks should behave before a generated box. if there is no generated box, the property is ignored. ...
...And 23 more matches
Node.insertBefore() - Web APIs
Web › API › Node › insertBefore
note that the copies made with clonenode() will not be automatically kept in sync. if the given child is a documentfragment, the entire contents of the documentfragment are moved into the child list of the specified parent node. ...
...note that the copies made with clonenode() will not be automatically kept in sync. if the given child is a documentfragment, the entire contents of the documentfragment are moved into the child list of the specified parent node. ...
...t node. if the given node already exists in the document, insertbefore() moves it from its current position to the new position. (that is, it will automatically be removed from its existing parent before appending it to the specified new parent.) this means that a node cannot be in two locations of the document simultaneously. note: the node.clonenode() can be used to make a copy of the node before appending it under the new parent. note that the copies made with clonenode() will not be automatically kept in sync. if the given child is a documentfragment, the entire contents of the documentfragment are moved into the child list of the specified parent node. ...
...And 10 more matches
ChildNode.before() - Web APIs
Web › API › ChildNode › before
the childnode.before() method inserts a set of node or domstring objects in the children list of this childnode's parent, just before this childnode. domstring objects are inserted as equivalent text nodes. syntax [throws, unscopable] void childnode.before((node or domstring)... nodes); parameters nodes a set of node or domstring objects to insert. exceptions hierarchyrequesterror: node cannot be inserted at the specified point in the hierarchy. ...
...(node or domstring)... nodes); parameters nodes a set of node or domstring objects to insert. exceptions hierarchyrequesterror: node cannot be inserted at the specified point in the hierarchy. ...
...rting an element var parent = document.createelement("div"); var child = document.createelement("p"); parent.appendchild(child); var span = document.createelement("span"); child.before(span); console.log(parent.outerhtml); // "<div><span></span><p></p></div>" inserting text var parent = document.createelement("div"); var child = document.createelement("p"); parent.appendchild(child); child.before("text"); console.log(parent.outerhtml); // "<div>text<p></p></div>" inserting an element and text var parent = document.createelement("div"); var child = document.createelement("p"); parent.appendchild(child); var span = document.createelement("span"); child.before(span, "text"); console.log(parent.outerhtml); // "<div><span></span>text<p></p></div>" childnode.before() is unscopable the be...
...And 8 more matches
-webkit-border-before - CSS: Cascading Style Sheets
it maps to a physical border depending on the element's writing mode, directionality, and text orientation. ...
...it maps to a physical border depending on the element's writing mode, directionality, and text orientation. ...
...it maps to a physical border depending on the element's writing mode, directionality, and text orientation. ...
...And 7 more matches
page-break-before - CSS: Cascading Style Sheets
this property has been replaced by the break-before property. the page-break-before css property adjusts page breaks before the current element. this property applies to block elements that generate a box. it won't apply on an empty <div> that won't generate a box. /* keyword values */ page-break-before: auto; page-break-before: always; page-break-before: avoid; page-break-before: left; page-break-before: right; page-break-before: recto; page-break-before: verso; /* global values */ page-break-before: inherit; page-break-before: initial; page-break-before: unset; syntax values auto initial value. automatic page breaks (neither forced nor forbidden). always always force page breaks before the element. ...
... recto if pages progress left-to-right, then this acts like right. if pages progress right-to-left, then this acts like left. ...
... recto if pages progress left-to-right, then this acts like right. if pages progress right-to-left, then this acts like left. verso if pages progress left-to-right, then this acts like left. ...
...And 7 more matches
BeforeInstallPromptEvent - Web APIs
this interface inherits from the event interface. ...
... this interface inherits from the event interface. ...
... this interface inherits from the event interface. ...
...And 4 more matches
Window: beforeprint event - Web APIs
the beforeprint event is fired when the associated document is about to be printed or previewed for printing. ...
... the beforeprint event is fired when the associated document is about to be printed or previewed for printing. ...
... the beforeprint event is fired when the associated document is about to be printed or previewed for printing. ...
...And 4 more matches
SyntaxError: missing ; before statement - JavaScript
what went wrong? there is a semicolon (;) missing somewhere. javascript statements must be terminated with semicolons. some of them are affected by automatic semicolon insertion (asi), but in this case you need to provide a semicolon, so that javascript can parse the source code correctly. ...
... what went wrong? there is a semicolon (;) missing somewhere. javascript statements must be terminated with semicolons. some of them are affected by automatic semicolon insertion (asi), but in this case you need to provide a semicolon, so that javascript can parse the source code correctly. ...
...r error, like not escaping strings properly, or using var wrongly. you might also have too many parenthesis somewhere. carefully check the syntax when this error is thrown. examples unescaped strings this error can occur easily when not escaping strings properly and the javascript engine is expecting the end of your string already. ...
...And 3 more matches
::-ms-ticks-before - Archive of obsolete content
other properties are ignored. ...
...other properties are ignored. ...
...other properties are ignored. ...
...And 2 more matches
MozBeforePaint
tes the time, in milliseconds since epoch, at which all animations started in the specified window during the current refresh interval should be considered to have started running. with that value in hand, you can then schedule all your subsequent animation frames. whenever you're ready to refresh your animation, you call the window.requestanimationframe() method. once you've called this, the mozbeforepaint event will be fired one time, when it's time for animations to be updated for the window's next animation frame. the timestamp property of this event will be set to the time when the animation frame is sampled; this is relevant when trying to synchronize mozrequestanimationframe animations with smil animations or css transitions. this allows multiple animations to remain in sync with one a...
...be updated for the window's next animation frame. the timestamp property of this event will be set to the time when the animation frame is sampled; this is relevant when trying to synchronize mozrequestanimationframe animations with smil animations or css transitions. this allows multiple animations to remain in sync with one another within the context of a given window. frame rate control mozbeforepaint won't fire more than a fixed number of times per second, e.g. 50 or 60. this is intentional, because modern operating systems and hardware won't let the browser display more frames than that anyway. limiting the frame rate avoids wasting work, thereby saving cpu usage and power and improving overall system performance. example this example performs a simple animation, moving a box a short ...
...this computes the current position for the animating box and updates the box's position on screen, and, if the animation sequence is not yet complete, calls window.re...
...And 2 more matches
BeforeUnloadEvent - Web APIs
when a non-empty string is assigned to the returnvalue event property, a dialog box appears, asking the users for confirmation to leave the page (see example below). when no value is provided, the event is processed silently. some implementations only show the dialog box if the frame or any embedded frame receives a user gesture or user interaction. see browser compatibility for more information. ...
...75" height="50" fill="#fff" stroke="#d4dde4" stroke-width="2px" /><text x="38.5" y="30" font-size="12px" font-family="consolas,monaco,andale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">event</text></a><polyline points="76,25 86,20 86,30 76,25" stroke="#d4dde4" fill="none"/><line x1="86" y1="25" x2="116" y2="25" stroke="#d4dde4"/><a xlink:href="/docs/web/api/beforeunloadevent" target="_top"><rect x="116" y="1" width="170" height="50" fill="#f4f7f8" stroke="#d4dde4" stroke-width="2px" /><text x="201" y="30" font-size="12px" font-family="consolas,monaco,andale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">beforeunloadevent</text></a></svg></div> a:hover text { fill: #0095dd; pointer-events: all;} bubbles ...
..."30" font-size="12px" font-family="consolas,monaco,andale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">beforeunloadevent</text></a></svg></div> a:hover text { fill: #0095dd; pointer-events: all;} bubbles no cancelable yes target objects defaultview interface event examples window.addeventlistener("beforeunload", function( event ) { event.returnvalue = "\o/"; }); // is equivalent to window.addeventlistener("beforeunload", function( event ) { event.preventdefault(); }); webkit-derived browsers don't follow the spec for the dialog box. ...
...And 2 more matches
Window: beforeunload event - Web APIs
if the user confirms, the browser navigates to the new page, otherwise it cancels the navigation. according to the specification, to show the confirmation dialog an event handler should call preventdefault() on the event. ...
...if the user confirms, the browser navigates to the new page, otherwise it cancels the navigation. according to the specification, to show the confirmation dialog an event handler should call preventdefault() on the event. ...
...thods: assigning a string to the event's returnvalue property returning a string from the event handler. some browsers used to display the returned string in the confirmation dialog, enabling the event handler to display a custom message to the user. however, this is deprecated and no longer supported in most browsers. to combat unwanted pop-ups, browsers may not display prompts created in beforeunload event handlers unless the page has been interacted with, or may even not display them at all. attaching an event handler/listener to window or document's beforeunload event prevents browsers from using in-memory page navigation caches, like firefox's back-forward cache or webkit's page cache. the html specification states that calls to window.alert(), window.confirm(), and window.prompt()...
...And 2 more matches
Window.onbeforeinstallprompt - Web APIs
the window.onbeforeinstallprompt property is an event handler for processing a beforeinstallprompt, which is dispatched on devices when a user is about to be prompted to "install" a web application. its associated event may be saved for later and used to prompt the user at a more suitable time. syntax window.addeventlistener("beforeinstallprompt", function(event) { ... }); window.onbeforeinstallprompt = function(event) { ...}; example the following example uses the beforeinstallprompt event to make an install button operable, by using the event inside a click handler. ...
...ociated event may be saved for later and used to prompt the user at a more suitable time. syntax window.addeventlistener("beforeinstallprompt", function(event) { ... }); window.onbeforeinstallprompt = function(event) { ...}; example the following example uses the beforeinstallprompt event to make an install button operable, by using the event inside a click handler. ...
...later and used to prompt the user at a more suitable time. syntax window.addeventlistener("beforeinstallprompt", function(event) { ... }); window.onbeforeinstallprompt = function(event) { ...}; example the following example uses the beforeinstallprompt event to make an install button operable, by using the event inside a click handler. ...
...And 2 more matches
WindowEventHandlers.onbeforeunload - Web APIs
the onbeforeunload property of the windoweventhandlers mixin is the eventhandler for processing beforeunload events. these events fire when a window is about to unload its resources. at this point, the document is still visible and the event is still cancelable. note: to combat unwanted pop-ups, some browsers don't display prompts created in beforeunload event handlers unless the page has been interacted with. moreover, some don't display them at all. syntax window.addeventlistener("beforeunload", function(event) { ... }); window.onbeforeunload = function(event) { ... }; typically, it is better to use window.addeventlistener() and the beforeunload event, instead of onbeforeunload. example this example prompts the user before unloading. the html specification states that authors should ...
...{ ... }); window.onbeforeunload = function(event) { ... }; typically, it is better to use window.addeventlistener() and the beforeunload event, instead of onbeforeunload. example this example prompts the user before unloading. the html specification states that authors should use the event.preventdefault() method instead of using event.returnvalue to prompt the user. ...
...ing event.returnvalue to prompt the user. window.addeventlistener('beforeunload', function (e) { // cancel the event e.preventdefault(); // if you prevent default behavior in mozilla firefox prompt will always be shown // chrome requires returnvalue to be set e.returnvalue = ''; }); guarantee the browser unload by removing the returnvalue property of the event window.addeventlistener('beforeunload', function (e) { // the absence of a returnvalue property on the event will guarantee the browser unload happens delete e['returnvalue']; }); notes when your page uses javascript to render content, the javascript may stop when leaving and then navigating back to the page. you can bind to window.onbeforeunload to prevent the browser from fully caching the page. if you do so, javascript...
...vent the browser from fully caching the page. if you do so, javascript in the page will be triggered on the subsequent return visit and update the content as desired. specifications the event was originally introduced by microsoft in internet explorer 4 and standardized in the html5 specification. specification status comment html living standardthe definition of 'onbeforeunload' in that specification. living standard html 5.1the definition of 'globaleventhandlers' in that specification. recommendation html5the definition of 'globaleventhandlers' in that specification. recommendation ...
about:debugging (before Firefox 68) - Firefox Developer Tools
you restart firefox. the big 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. updating a temporary add-on if you install the add-on in this way, what happens when you update the add-on's files? before firefox 48 if you change files that are loaded on demand, like content scripts or popups, then changes you make are picked up automatically, and you'll see them the next time the content script is loaded or the popup is shown. if you change files that stay loaded the whole time, like background scripts, then you can pick up changes you've made by disabling and then re-enabling the add-on in t...
...content script is loaded or the popup is shown. if you change files that stay loaded the whole time, like background scripts, then you can pick up changes you've made by disabling and then re-enabling the add-on in the about:addons page. if you change files that are only parsed at install time, like the manifest.json file, you'll need to restart firefox, then load the add-on again. note that before firefox 48, loading the add-on again by pressing "load temporary add-on" without restarting firefox does not work. firefox 48 onwards from firefox 48 onwards: as before: if you change files that are loaded on demand, like content scripts or popups, then changes you make are picked up automatically, and you'll see them the next time the content script is loaded or the popup is shown. the...
...tton, labeled "start": click this to start the service worker. clicking "debug" connects the javascript debugger and console to this worker. you can set breakpoints, step through code, watch variables, evaluate code, and so on: registering workers at first, you won't see any workers listed under service workers or shared workers. as soon as a worker is registered, the listing is updated: before firefox 47, service workers were only shown when they were actually running. unregistering service workers new in firefox 48. starting in firefox 48, you'll see a link named "unregister" next to each registered service worker: click the link to unregister the service worker. sending push events to service workers sending push events in about:debugging is new in firefox 47. to debug ...
HTMLElement: beforeinput event - Web APIs
the dom beforeinput event fires when the value of an <input>, <select>, or <textarea> element is about to be modified. the event also applies to elements with contenteditable enabled, and to any element when designmode is turned on. in the case of contenteditable and designmode, the event target is the editing host. if these properties apply to multiple elements, the editing host is the nearest ancestor element whose parent isn't editable. ...
...tiple elements, the editing host is the nearest ancestor element whose parent isn't editable. ...
...ult action update the dom element examples this example logs current value of the element immediately before replacing that value with the new one applied to the <input> element. html <input placeholder="enter some text" name="name"/> <p id="values"></p> javascript const input = document.queryselector('input'); const log = document.getelementbyid('values'); input.addeventlistener('beforeinput', updatevalue); function updatevalue(e) { log.textcontent = e.target.value; } result specifications specification status ui eventsthe definition of 'beforeinput event' in that specification. working draft ...
Document.onbeforescriptexecute - Web APIs
fired when the code in a <script> element declared in an html document is about to start executing. does not fire if the element is added dynamically, eg with appendchild(). syntax document.onbeforescriptexecute = funcref; funcref is a function reference, called when the event is fired. the event's target attribute is set to the script element that is about to be executed. ...
...does not fire if the element is added dynamically, eg with appendchild(). syntax document.onbeforescriptexecute = funcref; funcref is a function reference, called when the event is fired. the event's target attribute is set to the script element that is about to be executed. ...
WindowEventHandlers.onbeforeprint - Web APIs
the onbeforeprint property of the windoweventhandlers mixin is the eventhandler for processing beforeprint events for the current window. these events are raised before the print dialog window is opened. the beforeprint and afterprint events allow pages to change their content before printing starts (perhaps to remove a banner, for example) and then revert those changes after printing has completed. in general, you should prefer the use of an @media print css at-rule, but it may be necessary to use these events in some cases. syntax window.addeventlistener("beforeprint", function(event) { ... }); window.onbeforeprint = function(event) { ... }; polyfill safari does not implement these events, but you can create an equivalent result to the beforeprint event with window.matchmedia('print'). ...
...istener("beforeprint", function(event) { ... }); window.onbeforeprint = function(event) { ... }; polyfill safari does not implement these events, but you can create an equivalent result to the beforeprint event with window.matchmedia('print'). var mediaquerylist = window.matchmedia('print'); mediaquerylist.addlistener(function(mql) { if(mql.matches) { console.log('webkit equivalent of onbeforeprint'); } }); specification specification status comment html living standardthe definition of 'onbeforeprint' in that specification. living standard ...
ReferenceError: can't access lexical declaration`X' before initialization - JavaScript
the javascript exception "can't access lexical declaration `variable' before initialization" occurs when a lexical variable was accessed before it was initialized. this happens within any block statement, when let or const declarations are accessed before they are defined. message referenceerror: use before delaration (edge) referenceerror: can't access lexical declaration `x' before initialization (firefox) referenceerror: 'x' is not defined (chrome) error type referenceerror what went wrong? a lexical variable was accessed before it was initialized. this happens within any block statement, when let or const declarations are accessed before they are defined. examples invalid cases in this case, the variable "foo" is redeclared in the block statement using let. function test() { le...
...as accessed before it was initialized. this happens within any block statement, when let or const declarations are accessed before they are defined. examples invalid cases in this case, the variable "foo" is redeclared in the block statement using let. function test() { let foo = 33; if (true) { let foo = (foo + 55); // referenceerror: can't access lexical // declaration `foo' before initialization } } test(); valid cases to change "foo" inside the if statement, you need to remove the let that causes the redeclaration. function test(){ let foo = 33; if (true) { foo = (foo + 55); } } test(); ...
MozBeforeResize - Archive of obsolete content
general info specification mozilla specific interface event bubbles no cancelable no target window default action none properties property type description target read only eventtarget the event target (the topmost target in the dom tree). type read only domstring the type of event. bubbles read only boolean whether the event normally bubbles or not. cancelable read only boolean whether the event is cancellable or not. ...
beforecopy - Archive of obsolete content
the beforecopy event was part of copy logic override, a feature of the clipboard api added in january 2014 and removed in april 2016. ...
beforecut - Archive of obsolete content
the beforecut event was part of copy logic override, a feature of the clipboard api added in january 2014 and removed in april 2016. ...
beforepaste - Archive of obsolete content
the beforepaste event was part of copy logic override, a feature of the clipboard api added in january 2014 and removed in april 2016. ...
beforeselected - Archive of obsolete content
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. ...
insertbefore - Archive of obsolete content
« xul reference home insertbefore type: id when an element is in an overlay, the insertbefore attribute specifies the id of the element in the base window that the element should appear before. this value may be a comma-separated list of ids, which are scanned and the first one found in the window is used. ...
onbeforeaccept - Archive of obsolete content
« xul reference home onbeforeaccept type: script code the code in this attribute is called when the ok button is pressed or the acceptdialog method is called. returning false doesn't currently prevent the dialog from closing, but does prevent saving (bug 474527). ...
resizebefore - Archive of obsolete content
closest the element immediately to the left or above the splitter resizes. farthest the element that is the farthest away from the splitter to the left or above the splitter resizes. flex the closest flexible element resizes. ...
PR_INSERT_BEFORE
inserts an element before another element in a circular list. syntax #include <prclist.h> pr_insert_before ( prclist *elemp1 prclist *elemp2); parameters elemp1 a pointer to the element to be inserted. elemp2 a pointer to the element before which elemp1 is to be inserted. description pr_insert_before inserts the element specified by elemp1 into the circular list, before the element specified by elemp2. ...
BeforeInstallPromptEvent.prompt() - Web APIs
the prompt() method of the beforeinstallpromptevent interface allows a developer to show the install prompt at a time of their own choosing. syntax beforeinstallpromptevent.prompt() parameters none. returns an empty promise. example var istoosoon = true; window.addeventlistener("beforeinstallprompt", function(e) { if (istoosoon) { e.preventdefault(); // prevents prompt display // prompt later instead: settimeout(function() { istoosoon = false; e.prompt(); // throws if called more than once or default not prevented }, 10000); } // the event was re-dispatched in response to our request // ... }); ...
Element: beforescriptexecute event - Web APIs
cancelling the event prevents the script from executing. it is a proprietary event specific to gecko (firefox). ...
NodeIterator.pointerBeforeReferenceNode - Web APIs
the nodeiterator.pointerbeforereferencenode read-only property returns a boolean flag that indicates whether the nodefilter is anchored before (if this value is true) or after (if this value is false) the anchor node indicated by the nodeiterator.referencenode property. syntax flag = nodeiterator.pointerbeforereferencenode; example var nodeiterator = document.createnodeiterator( document.body, nodefilter.show_element, { acceptnode: function(node) { return nodefilter.filter_accept; } }, false ); flag = nodeiterator.pointerbeforereferencenode; specifications specification status comment domthe definition of 'nodeiterator.pointerbeforereferencenode' in that specification. living standard initial definition. ...
Range.setEndBefore() - Web APIs
the range.setendbefore() method sets the end position of a range relative to another node. the parent node of end of the range will be the same as that for the referencenode. syntax range.setendbefore(referencenode); parameters referencenode the node to end the range before. example var range = document.createrange(); var referencenode = document.getelementsbytagname("div").item(0); range.setendbefore(referencenode); specifications specification status comment domthe definition of 'range.setendbefore()' in that specification. living standard no change. document object model (dom) level 2 traversal and range specificationthe definition of 'range.setendbefore()' in that specification. obsolete initial specification. ...
Range.setStartBefore() - Web APIs
the range.setstartbefore() method sets the start position of a range relative to another node. the parent node of the start of the range will be the same as that for the referencenode. syntax range.setstartbefore(referencenode); parameters referencenode the node before which the range should start. example var range = document.createrange(); var referencenode = document.getelementsbytagname("div").item(0); range.setstartbefore(referencenode); specifications specification status comment domthe definition of 'range.setstartbefore()' in that specification. living standard no change. document object model (dom) level 2 traversal and range specificationthe definition of 'range.setstartbefore()' in that specification. obsolete initial specif...
Window.onmozbeforepaint - Web APIs
obsolete since gecko 11 (firefox 11 / thunderbird 11 / seamonkey 2.8)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 an event handler for the mozbeforepaint event. this is used in concert with the window.mozrequestanimationframe() method to perform smooth, synchronized animations from javascript code. syntax window.onmozbeforepaint = funcref; funcref is the handler function. example see window.mozrequestanimationframe() for an example. notes this event fires immediately before the browser window is repainted, if the event has been requested by one or more scripts calling window.mozrequestanimationframe(). the event handler receives as an input parameter an event whos...
substring-before - XPath
xslt/xpath reference: xslt elements, exslt functions, xpath functions, xpath axes the substring-before function returns a string that is the part of a given string before a given substring. syntax substring-before(haystack ,needle ) arguments haystack the string to be evaluated. part of this string will be returned. needle the substring to search for. everything before the first occurrence ofneedle inhaystack will be returned. returns a string. examples xpath example output substring-before('aa-bb','-') aa substring-before('aa-bb','a') (empty string) substring-before('aa-bb','b') aa- substring-before('aa-bb','q') (empty string) defined xpath 1.0 4.2 gecko support supported. ...
Index - Web APIs
Web › API › Index
tcontroller.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 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. 9 abortcontroller.signal api, 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. ...
...status api, guide, mobile, obsolete, overview the battery status api, more often referred to as the battery api, provides information about the system's battery charge level and lets you be notified by events that are sent when the battery level or charging status change. this can be used to adjust your app's resource usage to reduce battery drain when the battery is low, or to save changes before the battery runs out in order to prevent data loss. 264 batterymanager api, battery api, device api, interface, obsolete, reference, référence(2) the batterymanager interface provides ways to get information about the system's battery charge level. 265 batterymanager.charging api, battery api, needsmarkupwork, property, reference, référence(2) a boole...
...e events. these events occur when the battery level is updated. 273 beacon api guide, overview, web performance, user behavior tracker, user tracker the beacon interface is used to schedule an asynchronous and non-blocking request to a web server. beacon requests use the http post method and requests typically do not require a response. ...
...And 94 more matches
Index - Archive of obsolete content
avascript:tools, tools, web development, web development:tools in versions of firefox prior to firefox 3, all javascript exceptions were always logged into the error console if they remained unhandled at the time execution returned back into c++ code. as a result, if, for example, c++ code called a javascript component, which threw an exception, that exception would be logged to the console before control was returned to the c++ caller. 434 existing content this is a list of existing mozilla.org documentation. it needs to be checked, prioritized, and migrated. 435 extension frequently asked questions this is quick set of answers to the most common issues with extension development. they are currently written with mostly firefox in mind, but most ...
... first run jetpack lets you specify arbitrary content that will be shown to your users when they install your jetpack. you can also register a callback that will be called after installation. 511 me the jetpack.me namespace provides mechanisms for introspecting the dynamic state of your jetpack. the namespace currently lives in the future and must be imported before it is used: 512 settings the jetpack.storage.settings namespace allows jetpacks to specify user-configurable settings. 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 jetpac...
...pps from internet explorer to mozilla when netscape started the mozilla browser, it made the conscious decision to support w3c standards. as a result, mozilla is not fully backwards-compatible with netscape navigator 4.x and microsoft internet explorer legacy code; for example, mozilla does not support <layer> as i will discuss later. browsers, like internet explorer 4, that were built before the conception of w3c standards inherited many quirks. in this article, i will describe mozilla's quirks mode, which provides strong backwards html compatibility with internet explorer and other legacy browsers. 557 modularization techniques mozilla, xpcom the purpose of this document is provide all the information you need to create a new mozilla module or break existing cod...
...And 17 more matches
sslfnc.html
error code. description nss_init opens the certn.db, keyn.db, and secmod.db files (wheren is a numeric digit) in the specified directory. nss_init isnot idempotent, so call it only once. nss_init opens the database files read-only. if you are performing operations that require write permission, for example s/mime operations such as adding a certificate, use nss_initreadwrite instead. before calling nss_init, your program must call pr_init. the policy flags for all cipher suites are turned off by default, disallowing all cipher suites. therefore, an application cannot use nss to perform any cryptographic operations until after it enables appropriate cipher suites by calling one of the ssl export policy functions: nss_setdomesticpolicy, nss_setexportpolicy, and nss_setfrancepoli...
...ieve the error code. description nss_initreadwrite opens the certn.db, keyn.db, and secmod.db files (wheren is a numeric digit) with both read and write permission in the specified directory. nss_initreadwrite isnot idempotent, so call it only once. use nss_initreadwrite rather than nss_init if you are performing operations that require write permission, such as some s/mime operations. before calling nss_initreadwrite, your program must call pr_init. the policy flags for all cipher suites are turned off by default, disallowing all cipher suites. therefore, an application cannot use nss to perform any cryptographic operations until after it enables appropriate cipher suites by calling one of the ssl export policy functions. nss_nodb_init performs tasks required to run network s...
...success. if unsuccessful, secfailure. use pr_geterror to retrieve the error code. description nss_nodb_init opens only the temporary database and the internal pkcs #112 module. unlike nss_init, nss_nodb_init allows applications that do not have access to storage for databases to run raw crypto, hashing, and certificate functions. nss_nodb_init isnot idempotent, so call it only once. before calling nss_nodb_init, your program must call pr_init. the policy flags for all cipher suites are turned off by default, disallowing all cipher suites. therefore, an application cannot use nss to perform any cryptographic operations until after it enables appropriate cipher suites by calling one of the ssl export policy functions. ssl_optionsetdefault changes the default value of a spec...
...And 14 more matches
Observer Notifications
rs. this occurs after any profile migration. profile-after-change this is fired after all the observers for profile-do-change have been notified. you can register with nsicategorymanager to receive this notification. prior to firefox 3.5, this was available to observers observing the app-startup/xpcom-startup notification. final-ui-startup triggered just before the first window for the application is displayed. sessionstore-windows-restored sent by the session restore process to indicate that all initial browser windows have opened. note that while the window are open and the chrome loaded the tabs in the windows may still be being restored after this notification. note: this notification is specific to firefox and seamonkey 2.
...n' or 'restart'. profile-change-net-teardown the network connection is going offline at this point. note: the data value for this notification is always 'shutdown-persist'. profile-change-teardown part of the shutdown, profile data is still available at this point. note: the data value for this notification is always 'shutdown-persist'. ...
... profile-change-net-teardown the network connection is going offline at this point. note: the data value for this notification is always 'shutdown-persist'. profile-change-teardown part of the shutdown, profile 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. ...
...And 14 more matches
WebRequest.jsm
o write cross-browser add-on code. there are some differences between this api and chrome's, though: see chrome incompatibilities for the details. usage to import webrequest, use code like: let {webrequest} = cu.import("resource://gre/modules/webrequest.jsm", {}); the webrequest object has the following properties, each of which corresponds to a specific stage in executing a web request: onbeforerequest onbeforesendheaders onsendheaders onheadersreceived onresponsestarted oncompleted each of these objects defines two functions: addlistener(callback, filter, opt_extrainfospec) removelistener(callback) adding listeners use addlistener to add a listener to a particular event. it takes one mandatory argument and two optional arguments, as detailed below. name type ...
...opt_extrainfospec argument lets you pass extra instructions for the handling of events. the instructions you can pass here vary depending on the event you're listening to: see the event-specific documentation for details. in particular, "blocking" may be passed to several event types, and will make the event dispatch synchronous, so the browser will wait for the event listener to return before continuing with the request. this then enables the event listener to modify or cancel the request. see modifying & canceling requests. some examples of using addlistener(). to remove a listener for an event, call removelistener on the event in question, passing it the listener to remove. filtering the filter argument is the second argument to addlistener(). if you don't pass filter,...
...hat is, the webrequest event that your listener is attached to. for example, it obviously doesn't make sense to cancel a network request after it has completed. the general approach to modifying and canceling requests is this: first, pass an array containing the string "blocking" as the third argument to your addlistener() call. this tells the browser to wait for your event listener to return before continuing with the request. next, return an object from the 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 12 more matches
Menu - Archive of obsolete content
Archive › Mozilla › Jetpack › UI › Menu
me or content, as popup menus or context menus. two namespaces are associated with this api: jetpack.menu, which provides access to the browser's menus, and jetpack.menu, the constructor for making new menus. the api is fairly comprehensive, so you may want to start by reading through some examples. because it is still under development, the api currently lives in the future and must be imported before it is used: jetpack.future.import("menu"); menus all menus in jetpack are jetpack.menu objects, including both built-in firefox menus and menus that features create. to create a new menu, use one of the jetpack.menu constructors below. constructors jetpack.menu() creates an empty menu. jetpack.menu(menuitems) creates a menu with the given items. parameters menuitems an array of m...
...items) creates a menu with the given items. parameters menuitems an array of menuitems. jetpack.menu(properties) creates a menu with specific properties. parameters properties an object defining any of the properties below. the items property may be used to define an array of menuitems. ...
... menuitems an array of menuitems. jetpack.menu(properties) creates a menu with specific properties. parameters properties an object defining any of the properties below. the items property may be used to define an array of menuitems. properties property type description beforehide function a function invoked just before the menu is hidden. if the menu is a context menu, it is called as beforehide(menu, context) and otherwise as beforehide(menu). menu is the menu object to which beforehide is attached. context is an object describing the context in which the menu was shown. beforeshow function a function invoked just before the menu is shown. if the menu is a context menu, it is calle...
...And 10 more matches
Drawing graphics - Learn web development
e: you should generally set the size of the image using html attributes or dom properties, as explained above. you could use css, but the trouble then is that the sizing is done after the canvas has rendered, and just like any other image (the rendered canvas is just an image), the image could become pixellated/distorted. getting the canvas context and final setup we need to do one final thing before we can consider our canvas template finished. to draw onto the canvas we need to get a special reference to the drawing area called a context. this is done using the htmlcanvaselement.getcontext() method, which for basic usage takes a single string as a parameter representing the type of context you want to retrieve. in this case we want a 2d canvas, so add the following javascript line below th...
...vas.getcontext('2d'); note: other context values you could choose include webgl for webgl, webgl2 for webgl 2, etc., but we won't need those in this article. so that's it — our canvas is now primed and ready for drawing on! the ctx variable now contains a canvasrenderingcontext2d object, and all drawing operations on the canvas will involve manipulating this object. let's do one last thing before we move on. we'll color the canvas background black to give you a first taste of the canvas api. add the following lines at the bottom of your javascript: ctx.fillstyle = 'rgb(0, 0, 0)'; ctx.fillrect(0, 0, width, height); here we are setting a fill color using the canvas' fillstyle property (this takes color values just like css properties do), then drawing a rectangle that covers the entire ar...
...erences: we have set the last parameter of arc() to true, meaning that the arc is drawn counterclockwise, which means that even though the arc is specified as starting at -45 degrees and ending at 45 degrees, we draw the arc around the 270 degrees not inside this portion. if you were to change true to false and then re-run the code, only the 90 degree slice of the circle would be drawn. before calling fill(), we draw a line to the center of the circle. this means that we get the rather nice pac-man-style cutout rendered. if you removed this line (try it!) then re-ran the code, you'd get just an edge of the circle chopped off between the start and end point of the arc. this illustrates another important point of the canvas — if you try to fill an incomplete path (i.e. one that is not ...
...And 10 more matches
nsIHttpChannel
attribute is a hint to the channel to indicate whether or not the underlying http transaction should be allowed to be pipelined with other transactions. this should be set to false, for example, if the application knows that the corresponding document is likely to be very large. this attribute is true by default, though other factors may prevent pipelining. this attribute may only be set before the channel is opened. exceptions thrown ns_error_failure if set after the channel has been opened. redirectionlimit unsigned long this attribute specifies the number of redirects this channel is allowed to make. if zero, the channel will fail to redirect and will generate a ns_error_redirect_loop failure status. note: an http redirect r...
...he redirected channel's redirectionlimit attribute. the initial value for this attribute may be a configurable preference (depending on the implementation). referrer nsiuri get or set the uri of the http referer: header. this is the address (uri) of the resource from which this channel's uri was obtained (see rfc2616 section 14.36). this attribute may only be set before the channel is opened. note: the channel may silently refuse to set the referer: header if the uri does not pass certain security checks (e.g., a "https://" url will never be sent as the referrer for a plaintext http request). the implementation is not required to throw an exception when the referrer uri is rejected. exceptions thrown ns_error_in_progress if se...
... ns_error_in_progress if set after the channel has been opened. ns_error_failure if used for setting referrer during visitrequestheaders(). getting the value will not throw. requestmethod acstring set or get the http request method (default is "get"). setter is case insensitive; getter returns an uppercase string. this attribute may only be set before the channel is opened. note: the data for a "post" or "put" request can be configured via nsiuploadchannel. however, after setting the upload data, it may be necessary to set the request method explicitly. the documentation for nsiuploadchannel has further details. exceptions thrown ns_error_in_progress if set after the channel has been opened. ...
...And 10 more matches
WebIDL bindings
rface, you need to do the following: if your interface doesn't inherit from any other interfaces, inherit from nswrappercache and hook up the class to the cycle collector so it will trace the wrapper cache properly. note that you may not need to do this if your objects can only be created, never gotten from other objects. if you also inherit from nsisupports, make sure the nsisupports comes before the nswrappercache in your list of parent classes. if your interface does inherit from another interface, just inherit from the c++ type that the other interface corresponds to. if you do need to hook up cycle collection, it will look like this in the common case of also inheriting from nsisupports: // add strong pointers your class holds here. if you do, change to using // ns_impl_cycle_co...
...ring& (outparam) nsastring& (outparam) nsstring& (outparam) nsstring any any is represented in three different ways, depending on use: any arguments become js::handle<js::value>. they will be in the compartment of the passed-in jscontext. any return values become a js::mutablehandle<js::value> out param appended to the argument list. this comes after all idl arguments, but before the errorresult&, if any, for the method. the return value is allowed to be in any compartment; bindings will wrap it into the context compartment as needed. any dictionary members and sequence elements become js::value. the dictionary members and sequence elements are guaranteed to be marked by whomever puts the sequence or dictionary on the stack, using sequencerooter and dictionaryrooter. ...
... correspond to these c++ function declarations: float myattr(); void setmyattr(float value); double mymethod(const nullable<double>& arg); domstring strings are reflected in three different ways, depending on use: string arguments become const nsastring&. string return values become a mozilla::dom::domstring& out param appended to the argument list. this comes after all idl arguments, but before the errorresult&, if any, for the method. note that this allows callees to declare their methods as taking an nsastring& or nsstring& if desired. strings in sequences, dictionaries, owning unions, and variadic arguments become nsstring. nullable strings are represented by the same types as non-nullable ones, but the string will return true for domstringisnull(). returning null as a string valu...
...And 10 more matches
Box-shadow generator - CSS: Cascading Style Sheets
ype="move-up"> </div> <div class="button" data-type="move-down"> </div> </div> <div id="stack_container"></div> </div> <div id="preview_zone"> <div id="layer_menu" class="col span_12"> <div class="button" id="element" data-type="subject" data-title="element"> element </div> <div class="button" id="before" data-type="subject" data-title=":before"> :before <span class="delete" data-type="disable"></span> </div> <div class="button" id="after" data-type="subject" data-title=":after"> :after <span class="delete" data-type="disable"></span> </div> <div class="u...
...ta-title=":before"> :before <span class="delete" data-type="disable"></span> </div> <div class="button" id="after" data-type="subject" data-title=":after"> :after <span class="delete" data-type="disable"></span> </div> <div class="ui-checkbox" data-topic='before' data-label=":before"></div> <div class="ui-checkbox" data-topic='after' data-label=":after"></div> </div> <div id="preview"> <div id="obj-element"> <div class="content"> </div> <div id="obj-before"> </div> <div id="obj-after"> </div> </div> </div> ...
...s="menu"></div> <div class="title"> css code </div> <div class="group" style="border-top-left-radius: 0;"> <div class="output" data-topic="element" data-name="element" data-prop="width height background-color position=[relative] box-shadow"> </div> <div class="output" data-topic="before" data-name="element:before" data-prop="content=[&quot;&quot;] position=[absolute] width height top left z-index background-color box-shadow transform -webkit-transform -ms-transform"> </div> <div class="output" data-topic="after" data-name="element:after" data-prop="content=[&quot;&quot;] position=[absolute] w...
...And 10 more matches
Introduction to Public-Key Cryptography - Archive of obsolete content
" 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. encryption and decryption allow two communicating parties to disguise information they send to each other. the sender encrypts, or scrambles, information before sending it. the receiver decrypts, or unscrambles, the information after receiving it. while in transit, the encrypted information is unintelligible to an intruder. tamper detection allows the recipient of information to verify that it has not been modified in transit. any attempt to modify data or substitute a false message for a legitimate one will be detected. authentication allows the recip...
...t, or other commonly used personal ids, a certificate provides generally recognized proof of a person's identity. public-key cryptography uses certificates to address the problem of impersonation. to get a driver's license, you typically apply to a government agency, such as the department of motor vehicles, which verifies your identity, your ability to drive, your address, and other information before issuing the license. to get a student id, you apply to a school or college, which performs different checks (such as whether you have paid your tuition) before issuing the id. to get a library card, you may need to provide only your name and a utility bill with your address on it. certificates work much the same way as any of these familiar forms of identification. certificate authorities (cas) ...
...s. they can be either independent third parties or organizations running their own certificate-issuing server software (such as red hat certificate system). the methods used to validate an identity vary depending on the policies of a given ca-just as the methods to validate other forms of identification vary depending on who is issuing the id and the purpose for which it will be used. in general, before issuing a certificate, the ca must use its published verification procedures for that type of certificate to ensure that an entity requesting a certificate is in fact who it claims to be. the certificate issued by the ca binds a particular public key to the name of the entity the certificate identifies (such as the name of an employee or a server). certificates help prevent the use of fake publi...
...And 9 more matches
UI pseudo-classes - Learn web development
t setting and controlling validation constraints in our next article — client-side form validation — but for now we'll keep things simple with regards to form validation, so it doesn't confuse things. styling inputs based on whether they are required or not one of the most basic concepts with regards to client-side form validation is whether a form input is required (it has to be filled in before the form can be submitted) or optional. <input>, <select>, and <textarea> elements have a required attribute available which, when set, means that you have to fill in that control before the form will successfully submit. for example: <form> <fieldset> <legend>feedback form</legend> <div> <label for="fname">first name: </label> <input id="fname" name="fname" type="text" re...
... buttons has the required attribute, all the radio buttons will be invalid until one is selected, but only the one with the attribute assigned will actually match :required. using generated content with pseudo-classes in previous articles, we've seen the usage of generated content, but we thought now would be a good time to talk about it in a bit more detail. the idea is that we can use the ::before and ::after pseudo-elements along with the content property to make a chunk of content appear before or after the affected element. the chunk of content is not added to the dom, so is invisible to screenreaders; it is part of the document's styles. because it is a pseudo element, it can be targetted with styles in the same way that any actual dom node can. this is really useful when you want to ...
...s in the same way that any actual dom node can. this is really useful when you want to add a visual indicator to an element, such as a label or icon, but don't want it to be picked up by assistive technologies. ...
...And 9 more matches
Cooperative asynchronous JavaScript: Timeouts and intervals - Learn web development
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. requestanimationframe() the modern version of setinterval(). ...
...depending on how processor-intensive these operations are, they can delay your async code even further, as any async code will execute only after the main thread is available. ...
...ode will execute only after the main thread is available. (in other words, when the stack is empty.) you will learn more on this matter as you progress through this article. in any case, these functions are used for running constant animations and other background processing on a web site or application. in the following sections we will show you how they can be used. settimeout() as we said before, settimeout() executes a particular block of code once after a specified time has elapsed. it takes the following parameters: a function to run, or a reference to a function defined elsewhere. a number representing the time interval in milliseconds (1000 miliseconds equals 1 second) to wait before executing the code. if you specify a value of 0 (or simply omit the value), the function will ru...
...And 9 more matches
CustomizableUI.jsm
awidgetid, aarea, aoldposition, anewposition) fired when a widget is moved within its area. awidgetid is the widget that was moved, aarea the area it was moved in, aoldposition its old position, and anewposition its new position. onwidgetremoved(awidgetid, aarea) fired when a widget is removed from its area. awidgetid is the widget that was removed, aarea the area it was removed from. ...
...t is moved within its area. awidgetid is the widget that was moved, aarea the area it was moved in, aoldposition its old position, and anewposition its new position. onwidgetremoved(awidgetid, aarea) fired when a widget is removed from its area. awidgetid is the widget that was removed, aarea the area it was removed from. onwidgetbeforedomchange(anode, anextnode, acontainer, aisremoval) fired before a widget's dom node is acted upon by customizableui (to add, move or remove it). anode is the dom node changed, anextnode the dom node (if any) before which a widget will be inserted, acontainer the actual dom container (could be an overflow panel in case of an overflowable toolbar), and awasremoval is true iff the action about to happen is the removal of the dom node. onwidgetafterdomchange(ano...
... onwidgetreset(anode, acontainer) fired after a reset to default placements moves a widget's node to a different location. ...
...And 9 more matches
NSS environment variables
w. variable type description introduced in version nsrandcount integer (byte count) sets the maximum number of bytes to read from the file named in the environment variable nsrandfile (see below). makes nsrandfile usable with /dev/urandom. 3.12.3 nsrandfile string (file name) uses this file to seed the pseudo random number generator. before 3.0 nss_allow_weak_signature_alg boolean (any non-empty value to enable) enables the use of md2 and md4 inside signatures. this was allowed by default before nss 3.12.3. 3.12.3 nss_debug_pkcs11_module string (module name) name the pkcs#11 module to be traced. pkcs #11 module logger 3.6 nss_default_db_type string ("dbm", "sql", or "exter...
...n. the default setting for this option is false. 3.12.5 nss_ssl_server_cache_mutex_timeout integer (seconds) timeout time to detect dead or hung process in multi-process ssl server. default is 30 seconds. 3.4 nss_strict_nofork string ("1", "disabled", or any other non-empty value) it is an error to try to use a pkcs#11 crypto module in a process before it has been initialized in that process, even if the module was initialized in the parent process. beginning in nss 3.12.3, softoken will detect this error. this environment variable controls softoken's response to that error. if set to to "1" or unset, softoken will trigger an assertion failure in debug builds, and will report an error in non-debug builds. if set to "disabled", s...
... in non-debug builds. if set to "disabled", softoken will ignore forks, and behave as it did in older versions. if set to any other non-empty value, softoken will report an error in both debug and non-debug builds. 3.12.3 nss_strict_shutdown string (any non-empty value) will trigger an assertion failure in debug builds when a program tries to shutdown nss before freeing all the resources it acquired from nss while nss was initialized. 3.5 nss_trace_ocsp boolean (any value to enable) enables ocsp tracing. the trace information is written to the file pointed by nspr_log_file (default stderr). see nss tracing 3.12 nss_use_decoded_cka_ec_point boolean (any value to enable) tells nss to send ec key points across...
...And 9 more matches
Bytecode Descriptions
eating objects newinit stack: ⇒ obj create and push a new object with no properties. format: jof_ic newobject, newobjectwithgroup operands: (uint32_t baseobjindex) stack: ⇒ obj create and push a new object of a predetermined shape. the new object has the shape of the template object script->getobject(baseobjindex). subsequent initprop instructions must fill in all slots of the new object before it is used in any other way. for jsop::newobject, the new object has a group based on the allocation site (or a new group if the template's group is a singleton). for jsop::newobjectwithgroup, the new object has the same group as the template object. format: jof_object, jof_ic object operands: (uint32_t objectindex) stack: ⇒ obj push a preconstructed object. going one step further than jsop:...
...jsop::resume. implements: generatoryield and asyncgeneratoryield. format: jof_resumeindex isgenclosing stack: val ⇒ val, res pushes a boolean indicating whether the top of the stack is magicvalue(js_generator_closing). asyncawait stack: value, gen ⇒ promise arrange for this async function to resume asynchronously when value becomes resolved. this is the last thing an async function does before suspending for an await expression. it coerces the awaited value to a promise and effectively calls .then() on it, passing handler functions that will resume this async function call later. see js::asyncfunctionawait. this instruction must appear only in non-generator async function scripts. gen must be the internal generator object for the current frame. after this instruction, the script should...
...etoawait gen asyncawait # resultpromise getaliasedvar ".generator" # resultpromise gen await # resolved gen resumekind afteryield asyncawait arranges for this frame to be resumed later and pushes its result promise. await then suspends the frame and removes it from the stack, returning the result promise to the caller. (if this async call hasn't awaited before, the caller may be user code. otherwise, the caller is self-hosted code using resumegenerator.) in async generators: ... # valuetoawait getaliasedvar ".generator" # valuetoawait gen await # resolved gen resumekind afteryield asyncawait is not used, so (1) the value returned to the caller by await is valuetoawait, not resultpromise; and (2) the ...
...And 9 more matches
Animated PNG graphics
Mozilla › Tech › APNG
o be displayed. the contents of the canvas are not necessarily available to the decoder. as per the png specification, if a 'bkgd' chunk exists it may be used to fill the canvas if there is no preferrable background. the output buffer is a pixel array with dimensions specified by the width and height parameters of the png 'ihdr' chunk. conceptually, each frame is constructed in the output buffer before being composited onto the canvas. the contents of the output buffer are available to the decoder. the corners of the output buffer are mapped to the corners of the canvas. fully transparent black means red, green, blue and alpha 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 (...
... for purposes of chunk descriptions, an unsigned int shall be a 32-bit unsigned integer in network byte order limited to the range 0 to (2^32)-1; an unsigned short shall be a 16-bit unsigned integer in network byte order with the range 0 to (2^16)-1; and a byte shall be an 8-bit unsigned integer with the range 0 to (2^8)-1. error handling apng is designed to allow incremental display of frames before the entire image has been read. this implies that some errors may not be detected until partway through the animation. it is strongly recommended that when any error is encountered decoders should discard all subsequent frames, stop the animation, and revert to displaying the default image. a decoder which detects an error before the animation has started should display the default image. an erro...
...etects an error before the animation has started should display the default image. an error message may be displayed to the user if appropriate. structure an apng stream is a normal png stream as defined in the png specification, with three additional chunk types describing the animation and providing additional frame data. to be recognized as an apng, an 'actl' chunk must appear in the stream before any 'idat' chunks. the 'actl' structure is described below. conceptually, at the beginning of each play the output buffer must be completely initialized to a fully transparent black rectangle, with width and height dimensions from the 'ihdr' chunk. the default image may be included as the first frame of the animation by the presence of a single 'fctl' chunk before 'idat'. otherwise, the default...
...And 9 more matches
Index
stealing the master password. now you might be interest in how to get the nss sources, building and testing nss. 3 building nss guide, nss, security this page has detailed information on how to build nss. because nss is a cross-platform library that builds on many different platforms and has many options, it may be complex to build. please read these instructions carefully before attempting to build. 4 cert_findcertbydercert nss no summary! 5 cert_findcertbyissuerandsn nss no summary! 6 certificate functions nss the public functions listed here are used to interact with certificate databases. 7 cryptography functions nss the public functions listed here perform cryptographic operations bas...
...fig_string pass a configuration string for the module being added to the database. -tempdir temporary-directory give a directory location where temporary files are created during the installation by the -jar option. if no temporary directory is specified, the current directory is used. usage and examples creating database files before any operations can be performed, there must be a set of security databases available. modutil can be used to create these files. the only required argument is the database that where the databases will be located. modutil -create -dbdir [sql:]directory adding a cryptographic module adding a pkcs #11 module means submitting a supporting library file, enabling its ciphers, and...
...ry relative to which files should be installed; for example, it may be the server's root directory. the %temp% directory is created at the beginning of the installation and destroyed at the end. the purpose of %temp% is to hold executable files (such as setup programs) or files that are used by these programs. files destined for the temporary directory are guaranteed to be in place before any executable file is run; they are not deleted until all executable files have finished. absolutepath specifies the destination directory of the file as an absolute path. executable specifies that the file is to be executed during the course of the installation. typically, this string is used for a setup program provided by a module vendor, such as a self-extracting setup ex...
...And 8 more matches
Using IndexedDB - Web APIs
stores, or delete object stores from the previous version that are no longer needed. if you need to change an existing object store (e.g., to change the keypath), then you must delete the old object store and create it again with the new options. (note that this will delete the information in the object store! if you need to save that information, you should read it out and save it somewhere else before upgrading the database.) trying to create an object store with a name that already exists (or trying to delete an object store with a name that does not already exist) will throw an error. if the onupgradeneeded event exits successfully, the onsuccess handler of the open database request will then be triggered. blink/webkit supports the current version of the spec, as shipped in chrome 23+ a...
...plicates // so we can't use a unique index. objectstore.createindex("name", "name", { unique: false }); // create an index to search customers by email. we want to ensure that // no two customers have the same email, so use a unique index. objectstore.createindex("email", "email", { unique: true }); // use transaction oncomplete to make sure the objectstore creation is // finished before adding data into it. objectstore.transaction.oncomplete = function(event) { // store values in the newly created objectstore. var customerobjectstore = db.transaction("customers", "readwrite").objectstore("customers"); customerdata.foreach(function(customer) { customerobjectstore.add(customer); }); }; }; as indicated previously, onupgradeneeded is the only place where ...
...tore has the key generator, the key for the name value is generated automatically. // the added records would be like: // key : 1 => value : "bill" // key : 2 => value : "donna" customerdata.foreach(function(customer) { objstore.add(customer.name); }); }; for more details about the key generator, please see "w3c key generators". adding, retrieving, and removing data before you can do anything with your new database, you need to start a transaction. transactions come from the database object, and you have to specify which object stores you want the transaction to span. once you are inside the transaction, you can access the object stores that hold your data and make your requests. next, you need to decide if you're going to make changes to the database or if you jus...
...And 8 more matches
Splitters - Archive of obsolete content
e the size of the sidebar panel by dragging the bar in-between the two frames. you can also hide the sidebar by clicking the notch. splitter element this feature is accomplished using an element called a splitter. it creates a skinny bar between two sections which allows these sections to be resized. ...
... state indicates the state of the splitter. ...
... 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. ...
...And 7 more matches
create fancy boxes - Learn web development
css boxes are the building blocks of any web page styled with css. making them nice looking is both fun and challenging. it's fun because it's all about turning a design idea into working code; it's challenging because of annoying constraints and crazy freedom in the use of css. let's do some fancy boxes. before we start getting into the practical side of it, make sure you are familiar with the css box model. it's also a good idea, but not a prerequisite, to be familiar with some css layout basics. on the technical side, creating fancy boxes are all about mastering css border and background properties and how to apply them to a given box. but beyond the technics its also all about unleashing your creativity. it will not be done in one day, and some web developers spend their whole life...
...mple piece of html possible, a simple element: <div class="fancy">hi! i want to be fancy.</div> ok, that's a very small bit of html, what can we tweak on that element? all of the following: its box model properties: width, height, padding, border, etc. its background properties: background, background-color, background-image, background-position, background-size, etc. its pseudo-element: ::before and ::after and some aside properties like: box-shadow, transform, outline, etc. so we have a very large playground. let the fun begin. box model tweak the box model alone allows us to do some basic stuff, like adding simple borders, making squares, etc.. it starts to get interesting when you push the properties to the limit by having negative padding and/or- margin by having border-radius l...
...ll get an ellipsis rather than a circle ;) */ width : 4em; height : 4em; /* and let's turn the square into a circle */ border-radius: 100%; } yes, we get a circle: backgrounds when we talk about a fancy box, the core properties to handle that are background-* properties. when you start fiddling with backgrounds it's like your css box is turned into a blank canvas you'll fill. before we jump to some practical examples, let's step back a bit as there are two things you should know about backgrounds. it's possible to set several backgrounds on a single box. they are stacked on top of each other like layers. backgrounds can be either solid colors or images: solid color always fills the whole surface but images can be scaled and positioned. <div class="fancy">hi! i want to...
...And 7 more matches
Index - Learn web development
rtain way. the enclosing tags can make a word or image hyperlink to somewhere else, can italicize words, can make the font bigger or smaller, and so on. for example, take the following line of content: 40 how the web works beginner, client, dns, http, ip, infrastructure, learn, server, tcp, l10n:priority this theory is not essential to writing web code in the short term, but before long you'll really start to benefit from understanding what's happening in the background. 41 installing basic software beginner, browser, learn, setup, tools, webmechanics, l10n:priority, text editor that looks like a scary list, but fortunately, you can get started in web development without knowing anything about most of these. in this article, we'll just set you up with a...
... useful background on the web — how it came about, what web standard technologies are, how they work together, why "web developer" is a great career to choose, and what kinds of best practices you'll learn about through the course. 45 what will your website look like? assets, beginner, composing, content, deprecated, design, fonts, learn, simple, l10n:priority, step by step before doing anything, you need some ideas. what should your website actually do? a website can do basically anything, but, for your first try, you should keep things simple. we'll start by creating a simple webpage with a heading, an image, and a few paragraphs. 46 how to contribute to the learning area on mdn beginner, contribute, documentation, guide, learn, mdn meta, l10n:priority ...
...econd), discusses what they are useful for, and considers their inherent issues. 52 general asynchronous programming concepts javascript, learn, promises, threads, asynchronous, blocking in this article, we'll run through a number of important concepts relating to asynchronous programming, and how this looks in web browsers and javascript. you should understand these concepts before working through the other articles in the module. 53 graceful asynchronous programming with promises beginner, codingscripting, guide, javascript, learn, promises, async, asynchronous, catch, finally, then promises are a comparatively new feature of the javascript language that allow you to defer further actions until after a previous action has completed, or respond to its f...
...And 7 more matches
content - CSS: Cascading Style Sheets
Web › CSS › content
annot be combined with other values */ content: normal; content: none; /* <image> values */ content: url("http://www.example.com/test.png"); content: linear-gradient(#e66465, #9198e5); /* alt text for generated content, added in the level 3 specification */ content: url("http://www.example.com/test.png") / "this is the alt text"; /* values below can only be applied to generated content using ::before and ::after */ /* <string> value */ content: "prefix"; /* <counter> values */ content: counter(chapter_counter); content: counters(section_counter, "."); /* attr() value linked to the html attribute value */ content: attr(value string); /* language- and position-dependent keywords */ content: open-quote; content: close-quote; content: no-open-quote; content: no-close-quote; /* except for nor...
...dependent keywords */ content: open-quote; content: close-quote; content: no-open-quote; content: no-close-quote; /* except for normal and none, several values can be used simultaneously */ content: open-quote chapter_counter; /* global values */ content: inherit; content: initial; content: unset; syntax values none the pseudo-element is not generated. normal computes to none for the ::before and ::after pseudo-elements. <string> specifies the "alt text" for the element. this value can be any number of text characters. non-latin characters must be encoded using their unicode escape sequences: for example, \000a9 represents the copyright symbol. <image> an <image>, denoted by the <url> or <gradient> data type, or part of the webpage, defined by the element() function, denoting the ...
...er combinations will not announce it. if the content conveys information that is critical to understanding the page's purpose, it is better to include it in the main document. accessibility support for css generated content – tink explanation of wcag, guideline 1.3 – mdn understanding success criterion 1.3.1 | w3c understanding wcag 2.0 formal definition initial valuenormalapplies to::before and ::after pseudo-elementsinheritednocomputed valueon elements, always computes to normal. on ::before and ::after, if normal is specified, computes to none. otherwise, for uri values, the absolute uri; for attr() values, the resulting string; for other keywords, as specified.animation typediscrete formal syntax normal | none | [ <content-replacement> | <content-list> ] [/ <string> ]?where <co...
...And 7 more matches
Event reference
fic browsers; for example, mozilla-specific events are listed so that add-ons can use them to interact with the browser. most common categories resource events event name fired when error a resource failed to load. abort the loading of a resource has been aborted. load a resource and its dependent resources have finished loading. beforeunload the window, the document and its resources are about to be unloaded. unload the document or a dependent resource is being unloaded. network events event name fired when online the browser has gained access to the network. offline the browser has lost access to the network. focus events event name fire...
...ioniteration a css animation is repeated. css transition events event name fired when transitionstart a css transition has actually started (fired after any delay). transitioncancel a css transition has been cancelled. transitionend a css transition has completed. ...
... been cancelled. transitionend a css transition has completed. transitionrun a css transition has begun running (fired before any delay starts). form events event name fired when reset the reset button is pressed submit the submit button is pressed printing events event name fired when beforeprint the print dialog is opened afterprint the print dialog is closed text composition events event name fired when compositionstart the composition of a passage of text is prepared (similar to keydown for a keyboard input, but works with other inputs such as speech recognition). compositionupdate a character is added to a passage...
...And 7 more matches
Index - MDN Web Docs Glossary: Definitions of Web-related terms
languages, data types in computer science, a boolean is a logical data type that can have only the values true or false. 37 boot2gecko boot2gecko, firefox os, glossary, infrastructure, intro boot2gecko (b2g) is the engineering codename for firefox os and refers to builds that haven't yet received official firefox os branding. (firefox os was also often called boot2gecko before the project had an official name.) 38 bootstrap bootstrap, css, glossary, intro, framework bootstrap is a free, open source html, css, and javascript framework for quickly building responsive websites. 39 bounding box bounding box, codingscripting, design, glossary the bounding box of an element is the smallest possible rectangle (aligned with the axes of...
...roperties. 190 gzip compression glossary, compression, gzip gzip is a file format used for file compression and decompression. it is based on the deflate algorithm that allows files to be made smaller in size which allows for faster network transfers. gzip is commonly supported by web servers and modern browsers, meaning that servers can automatically compress files with gzip before sending them, and browsers can uncompress files upon receiving them. 191 hmac cryptography, glossary, hash, security hmac is a protocol used for cryptographically authenticating messages. 192 hpkp glossary, security http public key pinning (hpkp) is a security feature that tells a web client to associate a specific cryptographic public key with a certain ...
...to achieve hardware-accelerated rendering. 301 openssl glossary, security openssl is an open-source implementation of ssl and tls. 302 opera browser browser, glossary, navigation, opera, opera browser opera is the fifth most used web browser, publicly released in 1996 and initially running on windows only. opera uses blink as its layout engine since 2013 (before that, presto). opera also exists in mobile and tablet versions. 303 operand codingscripting, glossary an operand is the part of an instruction representing the data manipulated by the operator. for example, when you add two numbers, the numbers are the operand and "+" is the operator. 304 operator codingscripting, glossary reserved syntax consisting of pu...
...And 6 more matches
How to build custom form controls - Learn web development
ss how, when, and whether building your own control makes sense, and what to consider when building a control is a requirement. note: we'll focus on building the control, not on how to make the code generic and reusable; that would involve some non-trival javascript code and dom manipulation in an unknown context, and that is out of the scope of this article. design, structure, and semantics before building a custom control, you should start by figuring out exactly what you want. this will save you some precious time. in particular, it's important to clearly define all the states of your control. to do this, it's good to start with an existing control whose states and behavior are well known, so that you can simply mimic those as much as possible. in our example, we will rebuild the <selec...
...ons are obvious so we will handle them, but it can be a real problem for exotic new controls. when it comes to standardized elements, of which the <select> is one, the specification authors spent an inordinate amount of time specifying all interactions for every use case for every input device. creating new controls is not that easy, especially if you are creating something that has not been done before, and therefore which nobody has the slightest idea of what the expected behaviors and interactions are. at least select has been done before, so we know how it should behave! designing new interactions is generally only an option for very large industry players who have enough reach that an interaction they create can become a standard. for example, apple introduced the scroll wheel with the ipo...
...l to life with javascript now that our design and structure are ready, we can write the javascript code to make the control actually work. warning: the following is educational code, not production code, and should not be used as-is. it is neither future-proof nor will not work on legacy browsers. it also has redundant parts that should be optimized in production code. why isn't it working? before starting, it's important to remember javascript in the browser is an unreliable technology. custom controls rely on javascript to tie everything together. however, there are cases in which javascript isn't able to run in the browser: the user has turned off javascript: this is unusual; very few people turn off javascript nowadays. the script did not load: this is one of the most common cases,...
...And 6 more matches
What is JavaScript? - Learn web development
ike a factory that takes in raw materials (the code) and outputs a product (the web page). a very common use of javascript is to dynamically modify html and css to update a user interface, via the document object model api (as mentioned above). note that the code in your web documents is generally loaded and executed in the order it appears on the page. if the javascript loads and tries to run before the html and css it is affecting has been loaded, errors can occur. you will learn ways around this later in the article, in the script loading strategies section. browser security each browser tab has its own separate bucket for running code in (these buckets are called "execution environments" in technical terms) — this means that in most cases the code in each tab is run completely separat...
...splay. if you swapped the order of the first two lines of code, it would no longer work — instead, you'd get an error returned in the browser developer console — typeerror: para is undefined. this means that the para object does not exist yet, so we can't add an event listener to it. note: this is a very common error — you need to be careful that the objects referenced in your code exist before you try to do stuff to them. interpreted versus compiled code you might hear the terms interpreted and compiled in the context of programming. in interpreted languages, the code is run from top to bottom and the result of running the code is immediately returned. you don't have to transform the code into a different form before the browser runs it. the code is received in its programmer-friend...
...for example, c/c++ are compiled into machine code that is then run by the computer. ...
...And 6 more matches
Shell global objects
lace any callback set by setinterruptcallback. interruptif(cond) requests interrupt callback if cond is true. if a callback function is set via timeout or setinterruptcallback, it will be called. no-op otherwise. invokeinterruptcallback(fun) forcefully set the interrupt flag and invoke the interrupt handler. if a callback function is set via timeout or setinterruptcallback, it will be called. before returning, fun is called with the return value of the interrupt handler. setinterruptcallback(func) sets func as the interrupt callback function. calling this function will replace any callback set by timeout. enablelastwarning() enable storing the last warning. disablelastwarning() disable storing the last warning. getlastwarning() returns an object that represents the last warning. cle...
...fun did. hook gets passed the requested code's url, and should return a string. notes: spidermonkey may assert if the returned code isn't close enough to the script's real code, so this function is not fuzzer-safe. the runtime can have only one source retrieval hook active at a time. if fun is not careful, hook could be asked to retrieve the source code for compilations that occurred long before it was set, and that it knows nothing about. the reverse applies as well: the original hook, that we reinstate after the call to fun completes, might be asked for the source code of compilations that fun performed, and which, presumably, only hook knows how to find. wrapwithproto(obj) wrap an object into a noop wrapper with prototype semantics. note: this is not fuzzing safe because it ca...
..., 'shrinking']) run the garbage collector. when obj is given, gc only its zone. if zone is given, gc any zones that were scheduled for gc via schedulegc. if shrinking is passed as the optional second argument, perform a shrinking gc rather than a normal gc. minorgc([abouttooverflow]) run a minor collector on the nursery. when abouttooverflow is true, marks the store buffer as about-to-overflow before collecting. gcparam(name [, value]) wrapper for js_[gs]etgcparameter. the name is one of: maxbytes maxmallocbytes gcbytes gcnumber mode unusedchunks totalchunks slicetimebudget markstacklimit highfrequencytimelimit highfrequencylowlimit highfrequencyhighlimit highfrequencyheapgrowthmax highfrequencyheapgrowthmin lowfrequencyheapgrowth dynamicheapgrowth dynami...
...And 6 more matches
nsITreeView
itreeview in lieu of dom methods for tree creation can improve performance dramatically, and removes the need to make changes to the tree manually when changes to the database occur. further information about creating treeviews is given in the xul tutorial. ...
...ree creation can improve performance dramatically, and removes the need to make changes to the tree manually when changes to the database occur. further information about creating treeviews is given in the xul tutorial. ...
... nsitreeselection the selection for this view. constants constant value description progress_normal 1 note: renamed from progressnormal in gecko 1.8 progress_undetermined 2 note: renamed from progressundetermined in gecko 1.8 progress_none 3 note: renamed from progressnone in gecko 1.8 drop_before -1 drop_on 0 drop_after 1 indropbefore 0 obsolete since gecko 1.8 indropon 1 obsolete since gecko 1.8 indropafter 2 obsolete since gecko 1.8 methods candrop() methods used by the drag feedback code to determine if a drag is allowable at the current location. to get the behavior where drops are only allowe...
...And 6 more matches
splitter - Archive of obsolete content
« xul reference home [ examples | attributes | properties | methods | related ] an element which should appear before or after an element inside a container. when the splitter is dragged, the sibling elements of the splitter are resized. if a grippy is placed inside the splitter, one sibling element of the splitter is collapsed when the grippy is clicked. more information is available in the xul tutorial. attributes collapse, resizeafter, resizebefore, 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...
...litter was dragged')"> <vbox id="example_vbox" /> </splitter> attributes collapse type: one of the values below determines which side of the splitter is collapsed when its grippy is clicked. if this attribute is not specified, the splitter will not cause a collapse. you should put a grippy element inside the splitter when it is used for collapsing. none no collapsing occurs. ...
...r> attributes collapse type: one of the values below determines which side of the splitter is collapsed when its grippy is clicked. if this attribute is not specified, the splitter will not cause a collapse. you should put a grippy element inside the splitter when it is used for collapsing. none no collapsing occurs. ...
...And 5 more matches
nsIContentPolicy - Archive of obsolete content
ument 6 indicates a dom document at the top-level (that is, directly within a browser tab). type_subdocument 7 indicates a document contained within another document (for example, <iframe> and <frame> elements). note: gecko uses type_internal_frame and type_internal_iframe in order to discern the difference internally. these types are mapped to type_subdocument before being passed into the implementation of the content policy and should not be used outside gecko code. type_refresh 8 indicates a timed refresh. shouldload() will never get this, because it does not represent content to be loaded (the actual load triggered by the refresh will go through shouldload() as expected). shouldprocess() will get this for, for example ...
...th window and worker contexts. type_imageset 21 indicates a request to load an <img> (with the srcset attribute or <picture>. type_web_manifest 22 indicates a request to load a web manifest. type_internal_script 23 an internal constant used to represent scripts loaded using <script> elements. important: this type is mapped to type_script before being passed to content policy implementations, and should not be used outside gecko core code. type_internal_worker 24 an internal constant used to represent scripts loaded through a dedicated worker. important: this type is mapped to type_script before being passed to content policy implementations, and should not be used outside gecko core code. ...
...nt scripts loaded through a dedicated worker. important: this type is mapped to type_script before being passed to content policy implementations, and should not be used outside gecko core code. type_internal_shared_worker 25 an internal constant used to represent scripts loaded through a shared worker. important: this type is mapped to type_script before being passed to content policy implementations, and should not be used outside gecko core code. type_internal_embed 26 an internal constant used to represent content loaded from <embed> elements. important: this type is mapped to type_object before being passed to content policy implementations, and should not be used outside gecko core code. ...
...And 5 more matches
Pseudo-classes and pseudo-elements - Learn web development
first line of the first paragraph bold you could chain the :first-child and ::first-line selectors together. try editing the previous live example so it uses the following css. we are saying that we want to select the first line, of the first <p> element, which is inside an <article> element. ...
... 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 someone to find and edit in the future. ...
... more valid use of these pseudo-elements is to insert an icon, for example the little arrow added in the example below, which is a visual indicator that we wouldn't want read out by a screenreader: these pseudo-elements are also frequently used to insert an empty string, which can then be styled just like any element on the page. ...
...And 5 more matches
Looping code - Learn web development
final-expression) { // code to run } here we have: the keyword for, followed by some parentheses. inside the parentheses we have three items, separated by semi-colons: an initializer — this is usually a variable set to a number, which is incremented to count the number of times the loop has run. it is also sometimes referred to as a counter variable. a condition — as mentioned before, this defines when the loop should stop looping. this is generally an expression featuring a comparison operator, a test to see if the exit condition has been met. a final-expression — this is always evaluated (or run) each time the loop has gone through a full iteration. it usually serves to increment (or in some cases decrement) the counter variable, to bring it closer to the point where t...
...ortant: with for — as with all loops — you must make sure that the initializer is incremented or, depending on the case, decremented, so that it eventually reaches the point where the condition is not true. if not, the loop will go on forever, and either the browser will force it to stop, or it will crash. this is called an infinite loop. exiting loops with break if you want to exit a loop before all the iterations have been completed, you can use the break statement. we already met this in the previous article when we looked at switch statements — when a case is met in a switch statement that matches the input expression, the break statement immediately exits the switch statement and moves onto the code after it. it's the same with loops — a break statement will immediately exit the...
...f all we have some variable definitions — we have an array of contact information, with each item being a string containing a name and phone number separated by a colon. next, we attach an event listener to the button (btn), so that when it is pressed, some code is run to perform the search and return the results. we store the value entered into the text input in a variable called searchname, before then emptying the text input and focusing it again, ready for the next search. note that we also run the tolowercase() method on the string, so that searches will be case-insensitive. now onto the interesting part, the for loop: we start the counter at 0, run the loop until the counter is no longer less than contacts.length, and increment i by 1 after each iteration of the loop. inside ...
...And 5 more matches
Handling common JavaScript problems - Learn web development
e. when developers make use of new/nascent javascript features (for example ecmascript 6 / ecmascript next features, modern web apis...) in their code, and find that such features don't work in older browsers. we'll explore all these problems and more below. fixing general javascript problems as we said in the previous article on html/css, you should make sure your code is working generally, before going on to concentrate on the cross-browser issues. if you are not already familiar with the basics of troubleshooting javascript, you should study that article before moving on. there are a number of common javascript problems that you will want to be mindful of, such as: basic syntax and logic problems (again, check out troubleshooting javascript). making sure variables, etc. are defined i...
... scope. incorrectly using functions inside loops — for example, in bad-for-loop.html (see source code), we loop through 10 iterations, each time creating a paragraph and adding an onclick event handler to it. ...
...this kind of operation has been made easier to handle by the introduction of promises to the javascript language. ...
...And 5 more matches
AsyncShutdown.jsm
managing safe shutdown of asynchronous services. firefox shutdown is composed of phases that take place sequentially. typically, each shutdown phase removes some capabilities from the application. for instance, at the end of phase profilebeforechange, no service is permitted to write to the profile directory (with the exception of telemetry). consequently, if any service has requested i/o to the profile directory before or during phase profilebeforechange, the system must be informed that these requests need to be completed before the end of phase profilebeforechange. failing to inform the system of this requirement can (and has been known to) cause data loss. example at some point during shutdown, the add-on manager needs to ensure that all add-ons have safely written their data to d...
...file directory before or during phase profilebeforechange, the system must be informed that these requests need to be completed before the end of phase profilebeforechange. failing to inform the system of this requirement can (and has been known to) cause data loss. example at some point during shutdown, the add-on manager needs to ensure that all add-ons have safely written their data to disk, before writing its own data. since the data is saved to the profile, this must be completed during phase profilebeforechange. asyncshutdown.profilebeforechange.addblocker( "add-on manager: shutting down", function condition() { let promise = ... // do whatever must be done before the end of phase profilebeforechange return promise; }, function info() { let status = ... // collect an...
...r( "add-on manager: shutting down", function condition() { let promise = ... // do whatever must be done before the end of phase profilebeforechange return promise; }, function info() { let status = ... // collect any information that may be useful for debugging shutdown issues with this blocker return status; } }); in this example, at some point during phase profilebeforechange, function condition will be called. phase profilebeforechange is guaranteed to not terminate until promise is either resolved or rejected. if, for some reason, promise is never resolved/rejected, firefox will crash during shutdown to avoid blocking system shutdown, preventing the user from restarting firefox or burning through a battery. in this case, a crash report is produced, with inform...
...And 5 more matches
NSS Tools modutil
rpose of "%temp%" is to hold executable files (such as setup programs) or files that are used by these programs. for example, a windows installation might consist of a setup.exe installation program, a help file, and a .cab file containing compressed information. all these files could be installed in the temporary directory. files destined for the temporary directory are guaranteed to be in place before any executable file is run; they are not deleted until all executable files have finished. absolutepath specifies the destination directory of the file as an absolute path. if both relativepath and absolutepath are specified, the installer attempts to use the relative path; if it is unable to determine a relative path, it uses the absolute path. executable specifies that the file is to be...
...en creating database files this example creates a set of security management database files in the specified directory: modutil -create -dbdir c:\databases the security module database tool displays a warning: warning: performing this operation while communicator is running couldcause corruption of your security databases. if communicator iscurrently running, you should exit communicator before continuing thisoperation. type 'q <enter>' to abort, or <enter> to continue: after you press enter, the tool displays the following: creating "c:\databases\key3.db"...done.creating "c:\databases\cert8.db"...done.creating "c:\databases\secmod.db"...done. displaying module information this example gives detailed information about the specified module: modutil -list "netscape internal pkcs...
...fied module a default provider for the rsa, dsa, and rc2 security mechanisms: modutil -default "cryptographic module" -dbdir c:\databases -mechanisms rsa:dsa:rc2 the security module database tool displays a warning: warning: performing this operation while communicator is running couldcause corruption of your security databases. if communicator iscurrently running, you should exit communicator before continuing thisoperation. type 'q <enter>' to abort, or <enter> to continue: after you press enter, the tool displays the following: using database directory c:\databases...successfully changed defaults. enabling a slot this example enables a particular slot in the specified module: modutil -enable "cryptographic module" -slot "cryptographic reader" -dbdir c:\databases the security modu...
...And 5 more matches
TPS Bookmark Lists
ark 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 bookmark item expected to be found after this bookmark; used only in verify and modify actions. before: the title of the bookmark item expected to be found before this bookmark; used only in verify and modify actions. changes: an object containing new properties to be set for this bookmark when this asset list is used in a modify action. the properties for this object include the uri, title, loadinsidebar, description, tags, keyword properties above, plus two additional properties: location: the ...
...uri: "http://www.google.com", title: "google", loadinsidebar: false, tags: [ "google", "computers", "misc" ] } livemark objects valid properties are: livemark: the livemark name. 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 only in verify and modify actions. before: the title of the bookmark item expected to be found before this livemark; used only in verify and modify actions. changes: an object containing new properties to be set for this livemark when this asset list is used in a modify action. the properties for this object include the livemark, siteuri, feeduri properties above, plus two additional properties: location: the full path of the folder tha...
...ark: "livemarkone", feeduri: "http://rss.wunderground.com/blog/jeffmasters/rss.xml", siteuri: "http://www.wunderground.com/blog/jeffmasters/show.html" } folder objects valid properties are: folder: the folder's name. required. description: the folder's description. optional. after: the title of the bookmark item expected to be found after this folder; used only in verify and modify actions. before: the title of the bookmark item expected to be found before this folder; used only in verify and modify actions. changes: an object containing new properties to be set for this folder when this asset list is used in a modify action. the properties for this object include the folder, description properties above, plus two additional properties: location: the full path of the folder that this fold...
...And 5 more matches
Index
Mozilla › Tech › XPCOM › Index
is faq usually just refers back directly to the appropriate answer, there. if you're looking here just to learn about nscomptrs, you'll get a better introduction in the getting started guide. 81 getting started guide xpcom an nscomptr is an owning reference. whatever it points to has been addrefed, counting the nscomptr as one of its `owners'. an nscomptr always calls release before letting go, whether the nscomptr is letting go so that it can point to a different object, or because the nscomptr is going out of scope. any time a new value is assigned into an nscomptr, the nscomptr automatically always releases its old referent, if any, and (unless you tell it you already have) addrefs the new. 82 reference manual xpcom this section will help you if you'r...
...bject, or because the nscomptr is going out of scope. any time a new value is assigned into an nscomptr, the nscomptr automatically always releases its old referent, if any, and (unless you tell it you already have) addrefs the new. 82 reference manual xpcom this section will help you if you're already familiar with nscomptr but you need details. if you've never use nscomptrs before, you might want to read the getting started guide first. if you're trying to fix a broken build, the faq might lead you to the answer more quickly. 83 status, recent changes, and plans xpcom no summary! 84 using nsiclassinfo xpcom if you use a c++ class which implements nsiclassinfo from javascript, then you don't have to explicitly call queryinterface on...
... 89 using the clipboard add-ons, clipboard, extensions, guide, mozilla, xpcom this section provides information about cutting, copying, and pasting to and from the clipboard. 90 weak reference xpcom in xpcom, a weak reference is a special object that contains a pointer to an xpcom object, but doesnot keep that object alive. if the referent object is destroyed before the weak reference, the pointer inside the weak reference is set to nsnull. 91 working with multiple versions of interfaces add-ons, extensions, xpcom in this short note we illustrate how one can update an xpcom module in order for it to work in both firefox 2 and firefox 3, even if the interfaces have changed in the interim. 92 working with out parameters add-...
...And 5 more matches
IAccessibleText
pically this feature would not be implemented by an application. however, if the application developer was not satisfied with how screen readers have handled the reading of sentences this boundary type could be implemented and screen readers could use the application's version of a sentence rather than the screen reader's. the rest of the boundary types must be supported. this enum is used in textbeforeoffset(), textatoffset(), and textafteroffset(). method overview hresult addselection([in] long startoffset, [in] long endoffset ); [propget] hresult attributes([in] long offset, [out] long startoffset, [out] long endoffset, [out] bstr textattributes ); [propget] hresult caretoffset([out] long offset ); [propget] hresult characterextents([in] long offset, [in] enum ia2coordinatetype coord...
...hresult addselection( [in] long startoffset, [in] long endoffset ); parameters startoffset starting offset ( 0 based). endoffset offset of first character after new selection() (0 based). return value e_inv...
...objects, then the offset in the higher level text() object would be at the embed character representing child text() object that contains the caret. for example, if the string "one two three" is implemented as a two text() objects, with a top level text() object containing an embed character "one ? three" and a child text() object containing "two" and if the caret is in the descendant object just before the 'o' in "two", then: the caretoffset for the "one ? three" object would be 4, matching the embed character</li> the caretoffset for "two" would be 2, matching the "o" the caret position/offset is that of the character logically following it, for example to the right of it in a left to right language. [propget] hresult caretoffset( [out] long offset ); parameters offset the returned offse...
...And 5 more matches
Drawing and Event Handling - Plugins
led by the browser: npp_handleevent: deliver a platform-specific event to the instance. npp_print: request a platform-specific print operation for the instance. npp_setwindow: set the window in which a plug-in draws. browser-side methods, called by the plug-in: npn_forceredraw: force a paint message to a windowless plug-in. npn_invalidaterect: invalidate an area in a windowless plug-in before repainting or refreshing. npn_invalidateregion: invalidate a region in a windowless plug-in before repainting or refreshing. printing the plug-in the browser calls the npp_print method to ask the plug-in instance to print itself. void npp_print(npp instance, npprint *printinfo); the instance parameter represents the current plug-in. the printinfo parameter determines the print mode. it is...
...n can set the pluginprinted field in its printinfo parameter to false (the default). this is a field of the _npfullprint substructure of the npprint structure. the browser displays the necessary print dialog boxes and calls npp_print again. this time, printinfo->mode should be set to np_embed. a full-page plug-in handles the print dialog boxes and printing process as it sees fit. in this case, before the browser displays any print dialog boxes, npp_print is called with printinfo->mode equal to np_full. on mac os, full-page printing requires that the field printinfo contain a standard mac os thprint (see printing.h). of course, npp_print is also called with printinfo->mode equal to np_embed when the instance is embedded. in this case, platformprint->embedprint.window contains the window in w...
...hese coordinates to call setorigin(portx, porty) to place the upper-left corner of its rectangle at (0,0). the mac os grafport structure's cliprgn field should be set to the clipping rectangle for the instance in port coordinates. because the plug-in and the browser share the same graphics port, they share the responsibility for managing it correctly. the browser sets up the port for the plug-in before passing the plug-in an update event in two ways: the browser calls setorigin(npport->portx, npport->porty). this method makes the instance's upper-left coordinate equal to (0,0). the browser sets the port's clip region to the region of the plug-in currently visible (not scrolled off the page, obscured by floating palettes, or otherwise hidden). however, for the plug-in to draw at any other ...
...And 5 more matches
Element.insertAdjacentElement() - Web APIs
the insertadjacentelement() method of the element interface inserts a given element node at a given position relative to the element it is invoked upon. syntax targetelement.insertadjacentelement(position, element); parameters position a domstring representing the position relative to the targetelement; must match (case-insensitively) one of the following strings: 'beforebegin': before the targetelement itself. 'afterbegin': just inside the targetelement, before its first child. 'beforeend': just inside the targetelement, after its last child. 'afterend': after the targetelement itself. element the element to be inserted into the tree. return value the element that was inserted, or null, if the insertion failed. exceptions exception explanation ...
...he targetelement itself. element the element to be inserted into the tree. return value the element that was inserted, or null, if the insertion failed. exceptions exception explanation syntaxerror the position specified is not a recognised value. typeerror the element specified is not a valid element. ...
...e inserted into the tree. return value the element that was inserted, or null, if the insertion failed. exceptions exception explanation syntaxerror the position specified is not a recognised value. typeerror the element specified is not a valid element. ...
...And 5 more matches
WebKit CSS extensions - CSS: Cascading Style Sheets
webkit-only properties note: avoid using on websites. these properties will only work in webkit applications. ...
...note: avoid using on websites. these properties will only work in webkit applications. ...
...these properties will only work in webkit applications. ...
...And 5 more matches
test/utils - Archive of obsolete content
helper methods used in the commonjs unit testing suite. usage before and after helper functions before() and after() are available for running a function before or after each test in a suite. they're useful when you need to guarantee a particular state before running a test, and to clean up after your test. let { before, after } = require('sdk/test/utils'); let { search } = require('sdk/places/bookmarks'); exports.testcountbookmarks = function (assert, done) { search().on('end', function (results) { assert.equal(results, 0, 'should be no bookmarks'); done(); }); }; before(exports, function (name, assert) { removeallbookmarks(); }); require('sdk/test').run(exports); both before and after may be asynchronous. to make them asynchronous, pass a third argument done, which is ...
...(assert, done) { search().on('end', function (results) { assert.equal(results, 0, 'should be no bookmarks'); done(); }); }; before(exports, function (name, assert) { removeallbookmarks(); }); require('sdk/test').run(exports); both before and after may be asynchronous. ...
... asynchronous. to make them asynchronous, pass a third argument done, which is a function to call when you have finished: let { before, after } = require('sdk/test/utils'); let { search } = require('sdk/places/bookmarks'); exports.testcountbookmarks = function (assert, done) { search().on('end', function (results) { assert.equal(results, 0, 'should be no bookmarks'); done(); }); }; before(exports, function (name, assert, done) { removeallbookmarksasync(function () { done(); }); }); require('sdk/test').run(exports); globals functions before(exports, beforefn) runs beforefn before each test in the file. ...
...And 4 more matches
Chapter 5: Let's build a Firefox extension - Archive of obsolete content
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 the first start the profile manager will appear, where you can create the dev profile and configure its home-path. change your preferences for more efficient development before you get to work developing your extension, you’ll want to change some of your firefox preferences. this isn’t a requirement for extension development, but i recommend it as a way to work more efficiently. preference description value nglayout.debug.disable_xul_cache (not present in firefox 3.5+) ordinarily, firefox will cache xul documents after they h...
...e it in the spot numbered fixme: figure 5: finding merge points for overlays using the dom inspector putting overlays on the browser window now that you know the merge point for your overlay, you can create the overlay.xul file that will insert it (listing 3). in line 4, we identify the merge point as the menupop element; in lines 5–7, we have the code that adds the new menu item. the insertbefore attribute determines where the element gets added. test install and operational check this brings us to the point where we finally install our hello world extension. using the normal xpi-style installer would just be added trouble in this case, so we won’t use it. for source files under development, we do test installs. placing pointer files first, navigate to the profile folder of the curr...
...t the contents of that file to be the full path to the work folder for your extension source files, c:\extensions\helloworld. listing 3: additional content for overlay.xul <?xml version="1.0"?> <overlay id="helloworldoverlay" xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> <menupopup id="menu_toolspopup"> <menuitem id="helloworldmenuitem" label="hello, world!" insertbefore="sanitizeseparator" oncommand="window.opendialog('chrome://helloworld/content/clock.xul','clock','chrome,centerscreen,modal');"/> </menupopup> </overlay> phase 2: adding a function to display the time in phase 2, we will make it so that selecting the hello world menu item we created in phase 1 will display a window with the time (figure 6). fixme: figure 6: clock window produced by p...
...And 4 more matches
Template and Tree Listeners - Archive of obsolete content
lds the first of these is the simplest and involves two methods, willrebuild and didrebuild. you would implement this object with these two methods if you wish to be notified when the template is rebuilt using the builder's rebuild call. the template builder might also force a rebuild when the underlying data change notifications require it. the primary use of this listener is to store some state before the template is rebuilt and restore it afterwards. recall that when a template is rebuilt, all of the existing content will be removed and generated fresh. the willrebuild method of any listeners will be called before the content is removed, and didrebuild method will be called when the content has been regenerated. this listener will also work for tree builders, and will call the appropriate met...
...to assign a builder listener to a builder, use the addlistener method. ...
...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 be attached to a tree builder using the builder's addobserver method. you can add more than one observer if needed, and can remove them again with the builder's removeobserver method. the observer is always invoked before the appropriate operation is performed. for instance, the ontoggleopenstate method of any observers will be called before the tree item is opened. after the observers have finished, the tree builder opens the row and adds any child rows inside. note that you cannot cancel the operation from within the observer. some useful functions of the observer are the drag and drop related callbacks to handl...
...And 4 more matches
Client-side storage - Learn web development
nting our database. we will use this in a few places, so we've declared it globally here to make things easier. next, add the following to the bottom of your code: window.onload = function() { }; we will write all of our subsequent code inside this window.onload event handler function, called when the window's load event fires, to make sure we don't try to use indexeddb functionality before the app has completely finished loading (it could fail if we don't). inside the window.onload handler, add the following: // open our database; it is created if it doesn't already exist // (see onupgradeneeded below) let request = window.indexeddb.open('notes_db', 1); this line creates a request to open version 1 of a database called notes_db. if this doesn't already exist, it will be...
...ucture) of our database; that is, the set of columns (or fields) it contains. here we first grab a reference to the existing database from e.target.result (the event target's result property), which is the request object. this is equivalent to the line db = request.result; inside the onsuccess handler, but we need to do this separately here because the onupgradeneeded handler (if needed) will run before the onsuccess handler, meaning that the db value wouldn't be available if we didn't do this. we then use idbdatabase.createobjectstore() to create a new object store inside our opened database called notes_os. this is equivalent to a single table in a conventional database system. we've given it the name notes, and also specified an autoincrement key field called id — in each new record this...
...the idbdatabase.transaction() method. this transaction object allows us to access the object store so we can do something to it, e.g. add a new record. access the object store using the idbtransaction.objectstore() method, saving the result in the objectstore variable. add the new record to the database using idbobjectstore.add(). this creates a request object, in the same fashion as we've seen before. add a bunch of event handlers to the request and the transaction to run code at critical points in the lifecycle. once the request has succeeded, we clear the form inputs ready for entering the next note. once the transaction has completed, we run the displaydata() function again to update the display of notes on the page. displaying the data we've referenced displaydata() twice in our code ...
...And 4 more matches
Componentizing our React app - Learn web development
react doesn’t have any hard rules for what is and isn’t a component – that’s up to you! in this article we will show you a sensible way to break our app up into components. prerequisites: familiarity with the core html, css, and javascript languages, knowledge of the terminal/command line. objective: to show a sensible way of breaking our todo list app into components. ...
...ially valuable: making a component out of common ui elements allows you to change your code in one place and see those changes everywhere that component is used. you don't have to break everything out into components right away, either. let's take the second bullet point as inspiration and make a component out of the most reused, most important piece of the ui: a todo list item. ...
...oint as inspiration and make a component out of the most reused, most important piece of the ui: a todo list item. make a <todo /> before we can make a component, we should create a new file for it. in fact, we should make a directory just for our components. the following commands make a components directory and then, within that, a file called todo.js. make sure you're in the root of your app before you run these! mkdir src/components touch src/components/todo.js our new todo.js file is currently empty! open it up and give it its first line: import react from "react"; since we're going to make a component called todo, you can start adding the code for that to todo.js too, as follows. in this code, we define the function and export it on the same line: export default function todo() { ...
...And 4 more matches
IME handling guide
this document explains how gecko handles ime. introduction ime is an abbreviation of input method editor. this is a technical term from windows but these days, this is used on other platforms as well. ime is a helper application of a user's text input. it handles native key events before or after focused application (depending on the platform) and creates a composition string (a.k.a. preedit string), suggests a list of what the user attempts to input, commits composition string as a selected item off the list and commits composition string without any conversion. ime is used by chinese, japanese, korean and taiwan users for inputting chinese characters because the number of them is beyond thousands and cannot be input from the keyboard directly. however, especially on mobile devices n...
...ncommit this is used internally only. this is dispatched when a composition is committed with specific string. the mdata value is the commit string. this causes a dom text event without clause information and a dom compositionend event. ...
...event after dispatching ecompositionupdate event and/or ecompositionchange event if necessary. one of the other important jobs of this is, when a focused editor handles a dispatched ecompositionchange event, this modifies the stored composition string and its clause information. the editor refers the stored information for creating or modifying a text node representing a composition string. and before dispatching ecomposition* events, this class removes ascii control characters from dispatching composition event's data in the default settings. although, this can be disabled with "dom.compositionevent.allow_control_characters" pref. finally, this class guarantees that requesting to commit or cancel current composition to ime is perefored synchronously. see forcibly committing composition secti...
...And 4 more matches
OS.File for the main thread
see the promise object documentation for details. ...
... if true, file will be opened for writing. the file must not exist. if the file already exists, throw an error. cannot be used with truncate or existing. existing if true, the file must already exist. if the file does not exist, throw an error. cannot be used with create. append if true, the file will be opened for appending, meaning the equivalent of .setposition(0, pos_end) is executed before each write. the default is true, i.e. opening a file for appending. specify append: false to open the file in regular mode. optionsoptional platform-specific options for opening the file. for advanced users only. most users will never have need of these options. to specify options, pass an object that may contain some of the following flags: unixflags (ignored under non-unix platforms...
...let options = { winshare: 0 // exclusive lock on windows }; if (os.constants.libc.o_exlock) { // exclusive lock on *nix options.unixflags = os.constants.libc.o_exlock; } let file = yield os.file.open(..., options); then when you want to unlock the file so it can be edited from other places, close the file. file.close(); this example is from stackoverflow: os.file check last modified date before os.read os.file.openunique() creates and opens a file with a unique name. by default, generate a random hex number and use it to create a unique new file name. promise<object> openunique( in string path, [optional] in object options ) throws os.file.error arguments path the full native name of the file to open. optionsoptional additional options for file opening. this implementation...
...And 4 more matches
Index
69 js::sourcebufferholder jsapi reference, refe...
...ter, which is only called if the exception for an oom bubbles up and is not caught, the js::outofmemorycallback is called immediately at the oom site to allow the embedding to capture the current state of heap allocation before anything is freed. if the large-allocation-failure callback is called at all (not all allocation sites call the large-allocation-failure callback on failure), it is called before the out-of-memory callback; the out-of-memory callback is only called if the allocation still fails after the large-allocation-failure callback has returned. 69 js::sourcebufferholder jsapi reference, reference, référence(2), spidermonkey js::sourcebufferholder is the container class for passing in script source buffers to the js engine. this not only groups the buffer and ...
...rimitive value in *vp. 95 jsdeletepropertyop jsapi reference, reference, spidermonkey jsdeletepropertyop callback is a hook that applications may install to be called at some point during property access. a jsdeletepropertyop may be installed on a jsclass to hook property deletes. 96 jsenumerateop jsapi reference, spidermonkey jsenumerateop is called just before an object is enumerated (via a for...in statement, an array comprehension, or a call to js_enumerate). it should define any remaining lazy properties that should be enumerable but are not yet defined in obj. this hook does not implement iteration: once the properties are defined, the javascript engine can enumerate them. 97 jserrorformatstring jsapi reference, reference, référenc...
...And 4 more matches
Using microtasks in JavaScript with queueMicrotask() - Web APIs
a microtask is a short function which is executed after the function or program which created it exits and only if the javascript execution stack is empty, but before returning control to the event loop being used by the user agent to drive the script's execution environment. this event loop may be either the browser's main event loop or the event loop driving a web worker. this lets the given function run without the risk 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 wrapp...
...checks to see if the task is returning control to other javascript code. if not, it runs all of the microtasks in the microtask queue. the microtask queue is, then, processed multiple times per iteration of the event loop, including after handling events and other callbacks. second, if a microtask adds more microtasks to the queue by calling queuemicrotask(), those newly-added microtasks execute before the next task is run. that's because the event loop will keep calling microtasks until there are none left in the queue, even if more keep getting added. warning: since microtasks can themselves enqueue more microtasks, and the event loop continues processing microtasks until the queue is empty, there's a real risk of getting the event loop endlessly processing microtasks. be cautious with how ...
...alling microtasks until there are none left in the queue, even if more keep getting added. warning: since microtasks can themselves enqueue more microtasks, and the event loop continues processing microtasks until the queue is empty, there's a real risk of getting the event loop endlessly processing microtasks. be cautious with how you go about recursively adding microtasks. using microtasks before getting farther into this, it's important to note again that most developers won't use microtasks much, if at all. they're a highly specialized feature of modern browser-based javascript development, allowing you to schedule code to jump in front of other things in the long set of things waiting to happen on the user's computer. abusing this capability will lead to performance problems. enqueuei...
...And 4 more matches
SVGNumberList - Web APIs
tempts to modify the object will result in an exception being thrown. note: starting in gecko 5.0,the svgnumberlist dom interface is now indexable and can be accessed like arrays. ...
...modification_allowed_err is raised when the list corresponds to a read only attribute or when the object itself is read only. initialize(in svgnumber newitem) svgnumber clears all existing current items from the list and re-initializes the list to hold the single item specified by newitem. if the inserted item is already in a list, it is removed from its previous list before it is inserted into this list. the inserted item is the item itself and not a copy. the return value is the item inserted into the list. exceptions: a domexception with code no_modification_allowed_err is raised when the list corresponds to a read only attribute or when the object itself is read only. getitem(in unsigned long index) svgnumber returns t...
...eturns the specified item from the list. the returned item is the item itself and not a copy. any changes made to the item are immediately reflected in the list. the first item is number 0. exceptions: a domexception with code no_modification_allowed_err is raised when the list corresponds to a read only attribute or when the object itself is read only. insertitembefore(in svgnumber newitem, in unsigned long index) svgnumber inserts a new item into the list at the specified position. the first item is number 0. if newitem is already in a list, it is removed from its previous list before it is inserted into this list. the inserted item is the item itself and not a copy. if the item is already in this list, note that the index of the item to insert...
...And 4 more matches
SVGPathSegList - Web APIs
st interface this interface defines a list of svgpathseg objects. ...
...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 list before it is inserted into this list. the inserted item is the item itself and not a copy. the return value is the item inserted into the list. exceptions: a domexception with code no_modification_allowed_err is raised when the list cannot be modified. getitem(in unsigned long index) svg...
... returns the specified item from the list. the returned item is the item itself and not a copy. any changes made to the item are immediately reflected in the list. the first item is number 0. exceptions: a domexception with code no_modification_allowed_err is raised when the list cannot be modified. insertitembefore(in svgpathseg newitem, in unsigned long index) svgpathseg inserts a new item into the list at the specified position. the first item is number 0. if newitem is already in a list, it is removed from its previous list before it is inserted into this list. the inserted item is the item itself and not a copy. if the item is already in th...
...And 4 more matches
SVGPointList - Web APIs
s read only, which means that attempts to modify the object will result in an exception being thrown. ...
...orresponds 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 removed from its previous list before it is inserted into this list. the inserted item is the item itself and not a copy. the return value is the item inserted into the list. exceptions: a domexception with code no_modification_allowed_err is raised when the list corresponds to a read only attribute or when the object itself is read only. getitem(in unsigne...
... returned item is the item itself and not a copy. any changes made to the item are immediately reflected in the list. the first item is number 0. exceptions: a domexception with code no_modification_allowed_err is raised when the list corresponds to a read only attribute or when the object itself is read only. insertitembefore(in svgpoint newitem, in unsigned long index) svgpoint inserts a new item into the list at the specified position. the first item is number 0. if newitem is already in a list, it is removed from its previous list before it is inserted into this list. the inserted item is the item itself and not a copy. if the item is already in this list, note that the index of the item...
...And 4 more matches
SVGTransformList - Web APIs
fy the object will result in an exception being thrown. ...
..._allowed_err is raised when the list corresponds to a read only attribute or when the object itself is read only. initialize(in svgtransform newitem) svgtransform clears all existing current items from the list and re-initializes the list to hold the single item specified by the parameter. if the inserted item is already in a list, it is removed from its previous list before it is inserted into this list. the inserted item is the item itself and not a copy. the return value is the item inserted into the list. exceptions: a domexception with code no_modification_allowed_err is raised when the list corresponds to a read only attribute or when the object itself is read only. getitem(in unsigned long index) svgtransform return...
...eturns the specified item from the list. the returned item is the item itself and not a copy. any changes made to the item are immediately reflected in the list. the first item is number 0. exceptions: a domexception with code no_modification_allowed_err is raised when the list corresponds to a read only attribute or when the object itself is read only. insertitembefore(in svgtransform newitem, in unsigned long index) svgtransform inserts a new item into the list at the specified position. the first item is number 0. if newitem is already in a list, it is removed from its previous list before it is inserted into this list. the inserted item is the item itself and not a copy. if the item is already in this list, note that the index of the item to inser...
...And 4 more matches
Advanced techniques: Creating and sequencing audio - Web APIs
the key here is connecting the graph correctly, and also starting both oscillators: lfo.connect(amp.gain); osc.connect(amp).connect(audioctx.destination); lfo.start(); osc.start(); osc.stop(audioctx.currenttime + pulsetime); note: we also don't have to use the default wave types for either of these oscillators we're creating — we could use a wavetable and the periodic wave method as we did before. there is a multitude of possibilities with just a minimum of nodes. pulse user controls for the ui controls, let's expose both frequencies of our oscillators, allowing them to be controlled via range inputs. one will change the tone and the other will change how the pulse modulates the first wave: <label for="hz">hz</label> <input name="hz" id="hz" type="range" min="660" max="1320" value="88...
...th frequencies of our oscillators, allowing them to be controlled via range inputs. one will change the tone and the other will change how the pulse modulates the first wave: <label for="hz">hz</label> <input name="hz" id="hz" type="range" min="660" max="1320" value="880" step="1" /> <label for="lfo">lfo</label> <input name="lfo" id="lfo" type="range" min="20" max="40" value="30" step="1" /> as before, we'll vary the parameters when the range input values are changed by the user. let pulsehz = 880; const hzcontrol = document.queryselector('#hz'); hzcontrol.addeventlistener('input', function() { pulsehz = number(this.value); }, false); let lfohz = 30; const lfocontrol = document.queryselector('#lfo'); lfocontrol.addeventlistener('input', function() { lfohz = number(this.value); }, fal...
... audio api comes with two types of filter nodes: biquadfilternode and iirfilternode. for the most part a biquad filter will be good enough — it comes with different types such as lowpass, highpass, and bandpass. if you're looking to do something more bespoke, however, the iir filter might be a good option — see using iir filters for more information. wiring this up is the same as we've seen before. we create the biquadfilternode, configure the properties we want for it and connect it through our graph. different types of biquad filters have different properties — for instance setting the frequency on a bandpass type adjusts the middle frequency, however on a lowpass it would set the top frequency. let bandpass = audioctx.createbiquadfilter(); bandpass.type = 'bandpass'; bandpass.frequen...
...And 4 more matches
Window - Web APIs
Web › API › Window
these are properties of the window object that can be set to establish event handlers for the various things that can happen in the window that might be of interest. this interface inherits event handlers from the eventtarget interface and implements event handlers from windoweventhandlers. window.onappinstalled called when the page is installed as a webapp. see appinstalled event. window.onbeforeinstallprompt an event handler property dispatched before a user is prompted to save a web site to a home screen on mobile. window.ondevicelight an event handler property for any ambient light levels changes window.ondevicemotion called if accelerometer detects a change (for mobile devices) window.ondeviceorientation called when the orientation is changed (for mobile devices) window.ondevi...
...rientation changes. window.ondeviceproximity an event handler property for device proximity event window.ongamepadconnected represents an event handler that will run when a gamepad is connected (when the gamepadconnected event fires). window.ongamepaddisconnected represents an event handler that will run when a gamepad is disconnected (when the gamepaddisconnected event fires). window.onmozbeforepaint an event handler property for the mozbeforepaint event, which is sent before repainting the window if the event has been requested by a call to the window.mozrequestanimationframe() method. window.onpaint an event handler property for paint events on the window. window.onrejectionhandled an event handler for handled promise rejection events. window.onuserproximity an event handler pro...
...window.onuserproximity an event handler property for user proximity events. event handlers implemented from elsewhere globaleventhandlers.onabort called when the loading of a resource has been aborted, such as by a user canceling the load while it is still in progress windoweventhandlers.onafterprint called when the print dialog box is closed. see afterprint event. windoweventhandlers.onbeforeprint called when the print dialog box is opened. see beforeprint event. windoweventhandlers.onbeforeunload an event handler property for before-unload events on the window. globaleventhandlers.onblur called after the window loses focus, such as due to a popup. globaleventhandlers.onchange an event handler property for change events on the window. globaleventhandlers.onclick called after ...
...And 4 more matches
Value definition syntax - CSS: Cascading Style Sheets
ackets enclose several entities, combinators, and multipliers, then transform them as a single component. they are used to group components to bypass the precedence rules. bold [ thin && <length> ] this example matches the following values: bold thin 2vh bold 0 thin bold thin 3.5em but not: thin bold 3em, as bold is juxtaposed with the component defined by the brackets, it must appear before it. juxtaposition placing several keywords, literals or data types, next to one another, only separated by one or several spaces, is called juxtaposition. all juxtaposed components are mandatory and should appear in the exact order. bold <length> , thin this example matches the following values: bold 1em, thin bold 0, thin bold 2.5cm, thin bold 3vh, thin but not: thin 1em, bold, ...
... must appear at most one single time. bold, as it isn't a keyword allowed as value of any of the entity. note: the double ampersand has precedence over the double bar, meaning that bold || thin && <length> is equivalent to bold || [ thin && <length> ]. it describes bold, thin <length>, bold thin <length>, or thin <length> bold but not <length> bold thin as bold, if not omitted, must be placed before or after the whole thin && <length> component. single bar separating two or more entities by a single bar, |, means that all entities are exclusive options: exactly one of these options must be present. this is typically used to separate a list of possible keywords. <percentage> | <length> | left | center | right | top | bottom this example matches the following values: 3% 0 3.5em left...
...e time. note that multipliers cannot be added and have all precedence over combinators. asterisk (*) the asterisk multiplier indicates that the entity may appear zero, one or several times. bold smaller* this example matches the following values: bold bold smaller bold smaller smaller bold smaller smaller smaller, and so on. but not: smaller, as bold is juxtaposed, and must appear before any smaller keyword. plus (+) the plus multiplier indicates that the entity may appear one or several times. bold smaller+ this example matches the following values: bold smaller bold smaller smaller bold smaller smaller smaller, and so on. but not: bold, as smaller must appear at least one time. smaller, as bold is juxtaposed and must appear before any smaller keyword. question...
...And 4 more matches
Proxy Auto-Configuration (PAC) file - HTTP
xpression is translated to a regexp via subsitution of [.*?]. for a reliable way to use these regexp syntaxes, just use regexp instead. examples shexpmatch("http://home.netscape.com/people/ari/index.html" , "*/ari/*"); // returns true shexpmatch("http://home.netscape.com/people/montulli/index.html", "*/ari/*"); // returns false weekdayrange() syntax weekdayrange(wd1, wd2, [gmt]) note: (before firefox 49) wd1 must be less than wd2 if you want the function to evaluate these parameters as a range. see the warning below. parameters wd1 and wd2 one of the ordered weekday strings: "sun"|"mon"|"tue"|"wed"|"thu"|"fri"|"sat" gmt is either the string "gmt" or is left out. only the first parameter is mandatory. either the second, the third, or both may be left out. if only one pa...
...r, times are taken to be in gmt. otherwise, they are assumed to be in the local timezone. if both wd1 and wd1 are defined, the condition is true if the current weekday is in between those two ordered weekdays. bounds are inclusive, but the bounds are ordered. if the "gmt" parameter is specified, times are taken to be in gmt. otherwise, the local timezone is used. the order of the days matters; before firefox 49, weekdayrange("sun", "sat") will always evaluate to true. now weekdayrange("wed", "sun") will only evaluate true if the current day is wednesday or sunday. examples weekdayrange("mon", "fri"); // returns true monday through friday (local timezone) weekdayrange("mon", "fri", "gmt"); // returns true monday through friday (gmt timezone) weekdayrange("sat"); // retu...
...see the warning below. parameters day is the ordered day of the month between 1 and 31 (as an integer). 1|2|3|4|5|6|7|8|9|10|11|12|13|14|15|16|17|18|19|20|21|22|23|24|25|26|27|28|29|30|31 month is one of the order...
...And 4 more matches
panel - Archive of obsolete content
the screenshot below shows a panel whose content is built from the list of currently open tabs: panels are useful for presenting temporary interfaces to users in a way that is easier for users to ignore and dismiss than a modal dialog, since panels are hidden the moment users interact with parts of the application interface outside them. a panel's content is loaded as soon as it is created, before the panel is shown, and the content remains loaded when a panel is hidden, so it is possible to keep a panel around in the background, updating its content as appropriate in preparation for the next time it is shown. your add-on can receive notifications when a panel is shown or hidden by listening to its show and hide events. opening a panel will close any panel created by the panel() construc...
... urls point to scripts to load into the panel. the scripts must be packaged with the add-on under the add-on's data directory. that is, they can't refer to remote scripts. the urls are usually constructed using self.data.url(). from firefox 34, you can use "./my-script.js" as an alias for self.data.url("my-script.js"). content scripts specified by this property are loaded before those 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. contentstylefile string, array a url or an array of urls. the urls point to css style...
... property. contentstylefile string, array a url or an array of urls. the urls point to css stylesheets to load into the panel. the stylesheets must be packaged with the add-on under the add-on's data directory. that is, they can't refer to remote stylesheets. the urls are usually constructed using self.data.url(). stylesheets specified by this property are loaded before those specified by the contentstyle property. contentstyle string, array a string or an array of strings containing the texts of stylesheets to load. stylesheets specified by this property are loaded after those specified by the contentstylefile property. contentscriptwhen string when to load the content scripts. this may take one of the following v...
...And 3 more matches
Adding Toolbars and Toolbar Buttons - Archive of obsolete content
t is outside of the window element. if you put the toolbarpalette element inside the window element in your overlay, some weird errors will begin to happen. always set the label and tooltiptext attributes of a toolbarbutton. in the case of a toolbaritem element (discussed later), use the title attribute instead of label. tooltips are very important for users that want to know what a button does before clicking it. setting the image for a toolbar button is done with css: #xulschoolhello-hello-world-button { list-style-image: url("chrome://xulschoolhello/skin/hello-world.png"); } it's not really that simple to set the image for a toolbar button, because we need to consider the appearance of the button on different systems, and also consider the different button states, but we'll get into ...
...s add our own toolbar. this is done in the overlay as well. <window id="main-window"> <toolbox id="navigator-toolbox"> <toolbar id="xulschoolhello-toolbar" toolbarname="&xulschoolhello.toolbarname.label;" accesskey="&xulschoolhello.toolbar.accesskey;" customizable="true" mode="icons" context="toolbar-context-menu" defaultset="xulschoolhello-hello-world-button" insertbefore="personaltoolbar" /> </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 > toolbar...
...t doesn't need to be implemented again. the defaultset attribute lists the ids of the icons you want to include on your toolbar by default. it's a comma-separated list of ids, and it can also include other special values: spacer, separator and spring. spacer represents an empty button space, separator a vertical separation line and spring a flexible empty area that stretches. finally, the insertbefore attribute places our toolbar above the bookmarks toolbar. this is a matter of personal preference, but the mac os theme seems to be designed so that the bookmarks toolbar is always the last one (it has a lighter color than the rest). it also makes sense from a usability perspective, since bookmarks should be very easy to access for the user. that's it for the basics. with this knowledge you sho...
...And 3 more matches
MMgc - Archive of obsolete content
nters to these destroyed objects. if you get a crash dereferencing a pointer to a gc object, and the pointer was a member variable in an unmanaged (non-gc) object, check whether the unmanaged object is a gcroot. if it isn't, maybe it needs to be. finding missing write barriers there are some automatic aids in the mmgc library which can help you find missing write barriers. look in mmgc/gc.cpp. // before sweeping we check for missing write barriers bool gc::incrementalvalidation = false; // check for missing write barriers at every alloc bool gc::incrementalvalidationpedantic = false; if you suspect you have missing write barriers, turn these switches on in a debug build. (the second switch will slow your application down a lot more than the first switch, so you could try the first, then the se...
...hem. the problem with going from reference counting to pure mark/sweep garbage collection is that a lot of time may be spent in the garbage collector. this time will pause the entire application, and give the impression of poor performance. even with an incremental collector that doesn't have big pauses, a gc sweep only kicks in every so often, so memory usage can grow very quickly to a high peak before the gc collects unused objects. so, some kind of reference counting is still attractive to lower the amount of work the gc has to do, and to get more immediacy on memory reclamation. however, reference counting is also slow because the reference counts need to be constantly maintained. so, it's attractive to find some form of reference counting that doesn't require maintaining reference counts fo...
...s go through two steps, from gray to black and white to gray. whenever a pointer to a white object is written to a black object we have to intercept that write and remember to go back and put the white object in the work queue, that's what a write barrier does. ...
...And 3 more matches
Index - Archive of obsolete content
Archive › Mozilla › XUL › Index
31 browserid xul, xul reference no summary! 32...
...titlebarcolor xul attributes, xul reference no summary! 158 increment xul attributes, xul reference no summary! 159 index xul attributes, xul reference no summary! 160 inputtooltiptext xul attributes, xul reference no summary! 161 insertafter xul attributes, xul reference no summary! 162 insertbefore xul attributes, xul reference no summary! 163 instantapply xul attributes, xul reference no summary! 164 inverted xul attributes, xul reference no summary! 165 iscontainer xul attributes, xul reference no summary! 166 isempty xul attributes, xul reference no summary! 167 key xul attributes...
...a change event is fired in different ways for different xul input elements as...
...And 3 more matches
PopupEvents - Archive of obsolete content
: contextmenu this event is fired when a request is made to open a context menu, whether by the keyboard or mouse. 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. popupshown this event is fired on a menupopup, panel or tooltip once it is visible on screen. popuphiding this event is fired on a menupopup, panel or tooltip once it is about to be hidden. this may happen because the user selec...
... popuphiding this event is fired on a menupopup, panel or tooltip once it is about to be hidden. this may happen because the user selected an item from the menu, or it may be because the popup was closed by clicking elsewhere. popuphidden this event is fired on a menupopup, panel or tooltip once it has been hidden. the popupshowing event just before a popup is about to be displayed, a popupshowing event will fired on the popup. this will occur regardless of how the popup is opened, either from user interaction or from a script calling the openpopup or openpopupatscreen methods. the typical usage of a listener of the popupshowing event is to adjust the content of the popup based on context. for instance, right clicking on an image might displ...
...n methods. the typical usage of a listener of the popupshowing event is to adjust the content of the popup based on context. for instance, right clicking on an image might display items on a context menu pertaining to images, whereas clicking on a link would display only those items pertaining to links. within the listener for the popupshowing event, you can append to or modify the menu as needed before it is displayed. for examples of the use of the popupshowing event when used with context menus, see hiding and showing menu items based on context. however, this technique can be applied to any type of popup. in this example, a label within a panel is initialized with the current time. <panel id="time-panel" onpopupshowing="this.lastchild.value = (new date()).tolocaleformat('%t')"> <label valu...
...And 3 more matches
Positioning - Archive of obsolete content
e context menu just by clicking in the same location. for a tooltip, the position attribute controls how the tooltip is anchored to the element with the tooltip attribute. you wouldn't normally use the position attribute on a tooltip; instead you would just want the tooltip to appear at its default position which is near the mouse pointer. ...
...there are several possible values for the position attribute, described here, along with images which show how a popup would be aligned in each case. the following assumes a left to right user interface. ...
...ch that the bottom-left corner of the anchor is aligned with the upper-left corner of the popup. simple alignment values positions specified as a single word string are shortcuts for the values above. the following table shows the valid values, corresponding explicit (ie, 2 word) alignment values and an example of the alignment. single word alignment values example before_start the left side of the popup is aligned with the left side of the anchor, and the bottom of the popup is aligned along the top of the anchor. equivalent to topleft bottomleft before_end the right side of the popup is aligned with the right side of the anchor, and the bottom of the popup is aligned along the top of the anchor. equivalent to topright bottomright ...
...And 3 more matches
Audio for Web games - Game development
ur code on several devices and platforms to see how it works. volume programmatic volume control may be disabled in mobile browsers. the reason often given is that the user should be in control of the volume at the os level and this shouldn't be overridden. buffering and preloading likely as an attempt to mitigate runaway mobile network data use, we also often find that buffering is disabled before playback has been initiated. buffering is the process of the browser downloading the media in advance, which we often need to do to ensure smooth playback. the htmlmediaelement interface comes with lots of properties to help determine whether a track is in a state to be playable. note: in many ways the concept of buffering is an outdated one. as long as byte-range requests are accepted (which ...
......
...we can do this with javascript's async/await functionality. once they are available to play, we need to make sure they start at the correct point that other tracks might be playing at, so they sync up. let's create our audio context: // for cross browser compatibility const audiocontext = window.audiocontext || window.webkitaudiocontext; const audioctx = new audiocont...
...And 3 more matches
Styling web forms - Learn web development
styling essentials too. as well as the basic css tools covered above, we've also been provided with several selectors — ui pseudo-classes — that enable styling based on the current state of the ui. we cover these in detail in the next article, ui pseudo-classes. we'll walk through an example at the end of this article to give you some more ideas on basic form control styling and placement. before we do that however, we'd like to say a few words about specific aspects of form styling that are worth knowing about. fonts and text 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 ...
...valent input types! there's a lot of debate as to whether forms look better using the system default styles, or customized styles designed to match your content. this decision is yours to make, as the designer of your site, or web application. box sizing all text fields have complete support for every property related to the css box model, such as width, height, padding, margin, and border. as before, however, browsers rely on the system default styles when displaying these widgets. it's up to you to define how you wish to blend them into your content. if you want to keep the native look and feel of the widgets, you'll face a little difficulty if you want to give them a consistent size. this is because each widget has their own rules for border, padding and margin. to give the same size to s...
...ly:</label> <input type="email" id="mail" name="user_email"> </div> <div id="message"> <label for="msg">your message:</label> <textarea id="msg" name="user_message"></textarea> </div> <div class="button"> <button type="submit">send your message</button> </div> </form> add the above code into the body of your html. organizing your assets this is where the fun begins! before we start coding, we need three additional assets: the postcard background — download this image and save it in the same directory as your working html file. a typewriter font: the "secret typewriter" font from fontsquirrel.com — download the ttf file into the same directory as above. a handdrawn font: the "journal" font from fontsquirrel.com — download the ttf file into the same direct...
...And 3 more matches
Front-end web developer - Learn web development
welcome to our front-end web developer learning pathway! here we provide you with a structured course that will teach you all you need to know to become a front-end web developer. simply work through each section, learning new skills (or improving existing ones) as you go along. each section includes exercises and assessments to test your understanding before you move forward. subjects covered the subjects covered are: basic setup and learning how to learn web standards and best practices (such as accessibility and cross-browser compatibility) html, the language that gives web content structure and meaning css, the language used to style web pages javascript, the scripting language used to create dynamic functionality on the web tooling that is used to facilitate modern client-side w...
...each one is also self-contained. for example, if you already know html, you can skip ahead to the css section. prerequisites you don't need any previous knowledge to start this course. all you need is a computer that can run modern web browsers, an internet connection, and a willingness to learn. if you are not sure if front-end web development is for you, and/or you want a gentle introduction before starting a longer and more complete course, work through our getting started with the web module first. getting help we have tried to make learning front-end web development as comfortable as possible, but you will probably still get stuck because you don't understand something, or some code is just not working. don't panic. we all get stuck, whether we are beginner or professional web develop...
...he subject matter. completing the assessments confirms that you are ready to move on to the next module. modules introduction to html (15–20 hour read/exercises) multimedia and embedding (15–20 hour read/exercises) html tables (5–10 hour read/exercises) styling and layout with css time to complete: 90–120 hours prerequisites it is recommended that you have basic html knowledge before starting to learn css. you should at least study introduction to html first. how will i know i'm ready to move on? the assessments in each module are designed to test your knowledge of the subject matter. completing the assessments confirms that you are ready to move on to the next module. modules css first steps (10–15 hour read/exercises) css building blocks (35–45 hour read/exercis...
...And 3 more matches
Graceful asynchronous programming with Promises - Learn web development
used in that example. the trouble with callbacks to fully understand why promises are a good thing, it helps to think back to old-style callbacks and to appreciate why they are problematic. let's talk about ordering pizza as an analogy. there are certain steps that you have to take for your order to be successful, which doesn't really make sense to try to execute out of order, or in order but before each previous step has quite finished: you choose what toppings you want. this can take a while if you are indecisive, and may fail if you just can't make up your mind, or decide to get a curry instead. you then place your order. this can take a while to return a pizza and may fail if the restaurant does not have the required ingredients to cook it. you then collect your pizza and eat. this ...
...we're able to chain multiple asynchronous actions to occur one after another this way because each .then() block returns a new promise that resolves when the .then() block is done running. clever, right? using arrow functions, you can simplify the code even further: choosetoppings() .then(toppings => placeorder(toppings) ) .then(order => collectorder(order) ) .then(pizza => eatpi...
...element, add the following line: let promise = fetch('coffee.jpg'); this calls the fetch() method, passing it the url of the image to fetch from the network as a parameter. this can also take an options object as an optional second parameter, but we are just using the simplest version for now. we are storing the promise object returned by fetch() inside a variable called promise. as we said before, this object represents an intermediate state that is initially neither success nor failure — the official term for a promise in this state is pending. to respond to the successful completion of the operation whenever that occurs (in this case, when a response is returned), we invoke the .then() method of the promise object. the callback inside the .then() block (referred to as the execut...
...And 3 more matches
Inheritance in JavaScript - Learn web development
this function basically allows you to call a function defined somewhere else, but in the current context. 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. we want the teacher() constructor to take the same parameters as the person() ...
...evious addition: teacher.prototype = object.create(person.prototype); here our friend create() comes to the rescue again. in this case we are using it to create a new object and make it the value of teacher.prototype. the new object has person.prototype as its prototype and will therefore inherit, if and when needed, all the methods available on person.prototype. we need to do one more thing before we move on. after adding the last line, teacher.prototype's constructor property is now equal to person(), because we just set teacher.prototype to reference an object that inherits its properties from person.prototype! try saving your code, loading the page in a browser, and entering teacher.prototype.constructor into the console to verify. this can become a problem, so we need to set this righ...
...structor function that represents our person class. greeting() and farewell() are class methods. any methods you want associated with the class are defined inside it, after the constructor. in this example, we've used template literals rather than string concatenation to make the code easier to read. we can now instantiate object instances using the new operator, in just the same way as we did before: let han = new person('han', 'solo', 25, 'male', ['smuggling']); han.greeting(); // hi! i'm han let leia = new person('leia', 'organa', 19, 'female', ['government']); leia.farewell(); // leia has left the building. bye for now note: under the hood, your classes are being converted into prototypal inheritance models — this is just syntactic sugar. but i'm sure you'll agree that it's easier ...
...And 3 more matches
TypeScript support in Svelte - Learn web development
file to a scripts folder inside your project's root folder, and then run node scripts/setuptypescript.js. you can even use degit to download the script. that's what we will do to start porting our application to typescript. note: remember that you can run npx degit opensas/mdn-svelte-tutorial/07-typescript-support svelte-todo-typescript to get the complete to-do list application in javascript before you start porting it to typescript. go to the root directory of the project and enter these commands: npx degit sveltejs/template/scripts scripts # download script file to a scripts folder node scripts/setuptypescript.js # run it converted to typescript. you will need to re-run your dependency manager to get started. npm install ...
...te project you'd like to convert to typescript. just take into account that the svelte community is constantly improving svelte typescript support, so you should run npm update regularly to take advantage of the latest changes. note: if you find any trouble working with typescript inside a svelte application, have a look at this troubleshooting/faq section about typescript support. as we said before, typescript is a superset of javascript, so your application will run without modifications. currently you will be running a regular javascript application with typescript support enabled, without taking advantage of any of the features that typescript provides. you can now start adding types progressively. once you have typescript configured, you can start using it from a svelte component by ju...
...ce the export let todo line with the following: import type { todotype } from '../types/todo.type' export let todo: todotype note: another reminder — when importing a .ts file you have to omit the extension. check the import section of the typescript manual for more information. now from todos.svelte, we will instantiate a todo component with a literal object as its parameter before the call to the moreactions component, like this: <hr /> <todo todo={ { name: 'a new task with no id!', completed: false } } /> <!-- moreactions --> <moreactions {todos} add the lang='ts' to the <script> tag of the todos.svelte component, so that it knows to use the type checking we have specified. we will get the following error: by now you should get an idea about the kind...
...And 3 more matches
Setting up your own test automation environment - Learn web development
n enter the following command: node google_test_multiple if you are using a mac and do decide to test safari, you might get an error message along the lines of "could not create a session: you must enable the 'allow remote automation' option in safari's develop menu to control safari via webdriver." if you get this, follow the given instruction and try again. so here we've done the test as before, except that this time we've wrapped it inside a function, searchtest(). we've created new browser instances for multiple browsers, then passed each one to the function so the test is performed on all three browsers! fun huh? let's move on, look at the basics of webdriver syntax, in a bit more detail. webdriver syntax crash course let's have a look at a few key features of the webdriver syntax...
...xt, let's try entering some text into one of the form elements. add the following code and try running your test again: const input = driver.findelement(by.id('name')); input.sendkeys('filling in my form'); you can submit key presses that can't be represented by normal characters using properties of the webdriver.key object. ...
...e represented by normal characters using properties of the webdriver.key object. for example, above we used this construct to tab out of the form input before submitting it: driver.sleep(1000).then(function() { driver.findelement(by.name('q')).sendkeys(webdriver.key.tab); }); waiting for something to complete there are times where you'll want to make webdriver wait for something to complete before carrying on. for example if you load a new page, you'll want to wait for the page's dom to finish loading before you try to interact with any of its elements, otherwise the test will likely fail. in our google_test.js test for example, we included this block: driver.sleep(2000).then(function() { driver.gettitle().then(function(title) { if(title === 'webdriver - google search') { con...
...And 3 more matches
Command line crash course - Learn web development
contents page by page: less, cat manipulate and transform streams of text (for example changing all the instances of <div>s in an html file to <article>): awk, tr, sed note: there are a number of good tutorials on the web that go much deeper into the command line on the web — this is only a brief introduction! let's move forward and look at using a few of these tools on the command line. before you go any further, open your terminal program! navigation on the command line when you visit the command line you will inevitably need to navigate to a particular directory to "do something". all the operating systems (assuming a default setup) will launch their terminal program in your "home" directory, and from there you’re likely to want to move to a different place. the cd command lets ...
...as "wild card" characters, meaning "any sequence of characters". this allows you to run an operation against a potentially large number of files at once, all of which match the specified pattern. as an example, rm mdn-* would delete all files beginning with mdn-. rm mdn-*.bak would delete all files that start with mdn- and end with .bak. terminal — considered harmful? we’ve alluded to this before, but to be clear — you need to be careful with the terminal. simple commands do not carry too much danger, but as you start putting together more complex commands, you need to think carefully about what the command will do, and try testing them out first before you finally run them in the intended directory. let’s say you had 1000 text files in a directory, and you wanted to go through them ...
...o follow redirects using the -l flag. let's also look at the headers that developer.mozilla.org returns using curl's -i flag, and print all the location redirects it sends to the terminal, by piping the output of curl into grep (we will ask grep to return all the lines that contain the word "location"). ...
...And 3 more matches
Deploying our app - Learn web development
chunked, have tree-shaking applied, and that versions are "cache busted". running tests: these can range from "is this code formatted properly?" to "does this thing do what i expect?", and ensuring failing tests prevent deployment. actually deploying the updated code to a live url: or potentially a staging url so it can be reviewed first. note: cache busting is a new term that we haven't met before in the module. this is the strategy of breaking a browser's own caching mechanism, which forces the browser to download a new copy of your code. parcel (and indeed many other tools) will generate filenames that are unique to each new build. this unique filename "busts" your browser's cache, thereby making sure the browser downloads the fresh code each time an update is made to the deployed code. ...
...//github.com/new and create your own repository to host this code. give your repository a short, memorable name, without spaces in it (use hyphens to separate words), and a description, then click create repository at the bottom of the page. you should now have a "remote" url that points to your new github repo. this remote location needs to be added to our local git repository before we can push it up there, otherwise it won't be able to find it. you'll need to run a command with the following structure (use the provided https option for now — especially if you are new to github — not the ssh option): git remote add github https://github.com/yourname/repo-name.git so if your remote url was https://github.com/remy/super-website.git, as in the screenshot above, your c...
...l was https://github.com/remy/super-website.git, as in the screenshot above, your command would be git remote add github https://github.com/remy/super-website.git change the url to your own repository, and run it now. now we're ready to push our code to github; run the following command now: git push github master at this point you'll be prompted to enter a username and password before git will allow the push to be sent. this is because we used the https option rather than the ssh option, as seen in the screenshot earlier. for this you need your github username and then — if you do not have two-factor authentication (2fa) turned on — your github password. we would always encourage you to use 2fa if possible, but bear in mind that if you do, you'll also need to use a "person...
...And 3 more matches
Introducing a complete toolchain - Learn web development
t carefully. the smallest toolchain is one that has no links at all. you would handcode the html, use "vanilla javascript" (meaning no frameworks or intermediary languages), and manually upload it all to a server for hosting. however, more complicated software requirements will likely benefit from the usage of tools to help simplify the development process. in addition, you should include tests before you deploy to your production server to ensure your software works as intended — this already sounds like a necessary toolchain. for our sample project, we'll be using a toolchain specifically designed to aid our software development and support the technical choices made during the software design phase. we will however be avoiding any superfluous tooling, with the aim of keeping complexity t...
...ifically designed to aid our software development and support the technical choices made during the software design phase. we will however be avoiding any superfluous tooling, with the aim of keeping complexity to a minimum. for example, we could have included a tool to minimize our svg file sizes during build. however, this project has only 4 svg images, which were manually minified using svgo before adding them to the project. a couple of prerequisites besides the tools we're going to install that contribute to our toolchain, we mentioned two web services in the above list of tools. let's take this 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 previo...
...r from the install process, installing npm also installs a complimentary tool called npx. we will use npx later on this chapter to help run tools that are installed as local dependencies to the project. npm will be used to install subsequent parts of our toolchain. first of all, however, we'll install git to help with revision control. code revision control it's possible you've heard of "git" before. git is currently the most popular source code revision control tool available to developers — revision control provides many advantages, such as a way to backup your work in a remote place, and a mechanism to work in a team on the same project without fear of overwriting each other's code. it might be obvious to some, but it bears repeating: git is not the same thing as github. git is the rev...
...And 3 more matches
HTML parser threading
by obtaining a mutex once instead of having to synchronize thread on a per-tree op basis.) if the executor isn't reading from a stage, it calls nshtml5parser::parseuntilblocked() to parse potential document.write()-generated data into tree ops. the outer loop then has an inner loop that iterates over the tree ops in the executor's queue and calls perform on each one. parser termination is checked before each tree op for an early return, because, unfortunately, gecko expects parsers to be able to terminate immediately. after each tree op except the last one in the queue, the clock time is checked to see if runflushloop() has spent too much time without returning to the event loop. if too much time has been spent, a runnable for calling runflushloop() again is dispatched and an early return made b...
...e tree op stage), an owning reference to the nshtml5owningutf16buffer that contains the starting point of the speculation, an index into the nshtml5owningutf16buffer defining the exact starting point within the buffer, the line number of the tokenizer at that point and a snapshot of the tree op state. the line number and the snapshot are also added to the tree op that attempts to execute scripts (before flushing it). the tree builder snapshot contains a copy of the tree builder stack, a copy of the list of open formatting elements and copies of various fields that define the tree builder state. it contains all the information that is necessary to load back into the tree builder to restore it into a behaviorally equivalent state. the flush timer is disengaged, because it's not useful to make the ...
...er will produce tree ops so that they get flushed into the queue in the speculation object. if another tree op that attempts to execute a script is generated while speculating, another speculation object is initialized as described above and placed in the queue of speculation objects after the previous one. it is possible that the parser thread ends up parsing all remaining data into speculations before the main thread is ready to receive more tree ops. attempting to execute a script on the main thread, when the tree op executor executes a tree op that attempts to execute a script, the tree op is first checked for a tree builder state snapshot. there will be a snapshot if the tree op came from the parser thread. there won't be one if the tree op came from document.write() on the main thread (dis...
...And 3 more matches
Sqlite.jsm
ion 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 using sqlite.jsm. note: the sqlite.jsm javascript code module can only be used from chrome -- that is, from within the application itself or an add-on. before you can use this module, you need to import it into your scope: components.utils.import("resource://gre/modules/sqlite.jsm") obtaining a connection sqlite.jsm exports the sqlite symbol. this symbol is an object with a single function: openconnection. this function takes an object defining connection options: path (required) the database file to open. this can be an absolute or relative pat...
...pragma shrink_memory statement, which tells sqlite to shrink its memory usage (by clearing caches, etc). while calling this has the benefit of shrinking memory, it can make your database slower, especially if you will be interacting with it shortly after calling this function. this is because sqlite will need to page the database back into memory from disk. therefore, caution should be exercised before calling this function. this returns a promise that is resolved when the operation completes. discardcachedstatements() this function is used to discard cached statement instances, freeing memory in the process. active cached statements will not be discarded. therefore, it is safe to call this any time. this returns an integer count of the number of cached statements that were discarded. tabl...
...ee notes below. onrow (optional) function that is called when a row has been received. the return value is a promise that is resolved when the statement has finished execution. when a statement is executed via executecached(), the prepared statement object is cached inside the opened connection. the next time this same sql statement is executed (the sql argument is identical to one passed in before), the old statement object is reused. this saves time associated with parsing the sql statement and creating a new statement object. the downside is the cached statement object lingers in the opened connection, taking up memory. when a statement is executed via execute(), the underlying statement object is thrown away as soon as the statement finishes execution. executecached() is recommended f...
...And 3 more matches
NSS tools : signtool
d a file, it is difficult to claim later that you didn't sign it. in some situations, a digital signature may be considered as legally binding as a handwritten signature. therefore, you should take great care to ensure that you can stand behind any file you sign and distribute. ...
...digital signature may be considered as legally binding as a handwritten signature. therefore, you should take great care to ensure that you can stand behind any file you sign and distribute. for example, if you are a software developer, you should test your code to make sure it is virus-free before signing it. similarly, if you are a network administrator, you should make sure, before signing any code, that it comes from a reliable source and will run correctly with the software installed on the machines to which you are distributing it. before you can use netscape signing tool to sign files, you must have an object-signing certificate, which is a special certificate whose associated private key is used to create digital signatures. for testing purposes only...
...at will be distributed over the internet. * ca server software running on your corporate intranet or extranet. netscape certificate management system provides a complete management solution for creating, deploying, and managing certificates, including cas that issue object-signing certificates. you must also have a certificate for the ca that issues your signing certificate before you can sign files. if the certificate authority's certificate isn't already installed in your copy of communicator, you typically install it by clicking the appropriate link on the certificate authority's web site, for example on the page from which you initiated enrollment for your signing certificate. this is the case for some test certificates, as well as certificates issued by...
...And 3 more matches
How whitespace is handled by HTML, CSS, and in the DOM - Web APIs
ce? 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. take the following minimal example: <!doctype html> <h1> hello world! </h1> this source code contains a couple of line feeds after the doctype and a bunch of space characters before, after, and inside the <h1> element, but the browser doesn’t seem to care at all and just shows the words "hello world!" as if these characters didn’t exist at all: this is so that whitespace characters don't impact the layout of your page. creating space around and inside elements is the job of css. what does happen to whitespace? they don't just disappear, however. any whitespace cha...
... which contains a space, and the word "world!"). another text node (consisting only of tabs and spaces). because of this, it establishes what is called an inline formatting context. this is one of the possible layout rendering contexts that browser engines work with. ...
...nly of tabs and spaces). because of this, it establishes what is called an inline formatting context. this is one of the possible layout rendering contexts that browser engines work with. ...
...And 3 more matches
EventTarget.addEventListener() - Web APIs
ified type occurs. this must be an object implementing the eventlistener interface, or a javascript function. see the event listener callback for details on the callback itself. options optional an options object specifies characteristics about the event listener. the available options are: capture a boolean indicating that events of this type will be dispatched to the registered listener before being dispatched to any eventtarget beneath it in the dom tree. once a boolean indicating that the listener should be invoked at most once after being added. if true, the listener would be automatically removed when invoked. passive a boolean that, if true, indicates that the function specified by listener will never call preventdefault(). if a passive listener does call preventdefault(),...
... generate a console warning. see improving scrolling performance with passive listeners to learn more. mozsystemgroup a boolean indicating that the listener should be added to the system group. available only in code running in xbl or in the chrome of the firefox browser. usecapture optional a boolean indicating whether events of this type will be dispatched to the registered listener before being dispatched to any eventtarget beneath it in the dom tree. events that are bubbling upward through the tree will not trigger a listener designated to use capture. event bubbling and capturing are two ways of propagating events that occur in an element that is nested within another element, when both elements have registered a handle for that event. the event propagation mode determines the o...
...t) { // unable to preventdefault inside passive event listener invocation. event.preventdefault(); alert('inner1, passive, open new page'); } function nonepassivehandler(event) { event.preventdefault(); //event.stoppropagation(); alert('inner2, none-passive, default, not open new page'); } result click the outer, middle, inner containers respectively to see how the options work. before using a particular value in the options object, it's a good idea to ensure that the user's browser supports it, since these are an addition that not all browsers have supported historically. see safely detecting option support for details. other notes why use addeventlistener()? addeventlistener() is the way to register an event listener as specified in w3c dom. the benefits are as follows: ...
...And 3 more matches
HTMLSelectElement.add() - Web APIs
if this parameter is null (or the index does not exist), the new element is appended to the end of the collection. exceptions a domerror of the type hierarchyrequesterror if the item passed to the method is an ancestor of the htmlselectelement. ...
...if this parameter is null (or the index does not exist), the new element is appended to the end of the collection. exceptions a domerror of the type hierarchyrequesterror if the item passed to the method is an ancestor of the htmlselectelement. ...
...so the following is accepted. ... sel.add(opt1); sel.add(opt2); ... append to an existing collection var sel = document.getelementbyid("existinglist"); var opt = document.createelement("option"); opt.value = "3"; opt.text = "option: value 3"; sel.add(opt, null); /* takes the existing following select object: <select id="existinglist"> <option value="1">optio...
...And 3 more matches
KeyboardEvent.key - Web APIs
Web › API › KeyboardEvent › key
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 possibly an <input>, <textarea> or an element with htmlelement.contenteditable set to true, the beforeinput and input event types are fired in that order. note that some other implementations may fire keypress event if supported. the events will be fired repeatedly while the key is held down. a keyup event is fired once the key is released. this 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...
...g'), btnclearconsole = document.getelementbyid('btn-clear-console'); function logmessage(message) { document.getelementbyid("console-log").innerhtml += message + "<br>"; } textarea.addeventlistener('keydown', (e) => { if (!e.repeat) logmessage(`key "${e.key}" pressed [event: keydown]`); else logmessage(`key "${e.key}" repeating [event: keydown]`); }); textarea.addeventlistener('beforeinput', (e) => { logmessage(`key "${e.data}" about to be input [event: beforeinput]`); }); textarea.addeventlistener('input', (e) => { logmessage(`key "${e.data}" input [event: input]`); }); textarea.addeventlistener('keyup', (e) => { logmessage(`key "${e.key}" released [event: keyup]`); }); btnclearconsole.addeventlistener('click', (e) => { let child = consolelog.firstchild; while...
... case 1 when the shift key is pressed, a keydown event is first fired, and the key property value is set to the string shift. as we keep holding this key, the keydown event does not continue to fire repeatedly because it does not produce a character key. when key 2 is pressed, another keydown event is fired f...
...And 3 more matches
PerformanceResourceTiming - Web APIs
ring representing the type of resource that initiated the performance entry, as specified in performanceresourcetiming.initiatortype. performanceresourcetiming.nexthopprotocolread only a string representing the network protocol used to fetch the resource, as identified by the alpn protocol id (rfc7301). performanceresourcetiming.workerstartread only returns a domhighrestimestamp immediately before dispatching the fetchevent if a service worker thread is already running, or immediately before starting the service worker thread if it is not already running. if the resource is not intercepted by a service worker the property will always return 0. performanceresourcetiming.redirectstartread only a domhighrestimestamp that represents the start time of the fetch which initiates the redirect. ...
...always return 0. performanceresourcetiming.redirectstartread only a domhighrestimestamp that represents the start time of the fetch which initiates the redirect. performanceresourcetiming.redirectendread only a domhighrestimestamp immediately after receiving the last byte of the response of the last redirect. performanceresourcetiming.fetchstartread only a domhighrestimestamp immediately before the browser starts to fetch the resource. performanceresourcetiming.domainlookupstartread only a domhighrestimestamp immediately before the browser starts the domain name lookup for the resource. performanceresourcetiming.domainlookupendread only a domhighrestimestamp representing the time immediately after the browser finishes the domain name lookup for the resource. performanceresourceti...
...timing.domainlookupstartread only a domhighrestimestamp immediately before the browser starts the domain name lookup for the resource. performanceresourcetiming.domainlookupendread only a domhighrestimestamp representing the time immediately after the browser finishes the domain name lookup for the resource. performanceresourcetiming.connectstartread only a domhighrestimestamp immediately before the browser starts to establish the connection to the server to retrieve the resource. performanceresourcetiming.connectendread only a domhighrestimestamp immediately after the browser finishes establishing the connection to the server to retrieve the resource. ...
...And 3 more matches
SVGLengthList - Web APIs
hat attempts to modify the object will result in an exception being thrown. ...
...fication_allowed_err is raised when the list corresponds to a read only attribute or when the object itself is read only. initialize(in svglength newitem) svglength clears all existing current items from the list and re-initializes the list to hold the single item specified by the parameter. if the inserted item is already in a list, it is removed from its previous list before it is inserted into this list. the inserted item is the item itself and not a copy. the return value is the item inserted into the list. exceptions: a domexception with code no_modification_allowed_err is raised when the list corresponds to a read only attribute or when the object itself is read only. getitem(in unsigned long index) svglength returns the sp...
... returns the specified item from the list. the returned item is the item itself and not a copy. any changes made to the item are immediately reflected in the list. the first item is number 0. exceptions: a domexception with code no_modification_allowed_err is raised when the list corresponds to a read only attribute or when the object itself is read only. insertitembefore(in svglength newitem, in unsigned long index) svglength inserts a new item into the list at the specified position. the first item is number 0. if newitem is already in a list, it is removed from its previous list before it is inserted into this list. the inserted item is the item itself and not a copy. if the item is already in this list, note that the index of the item to insert befor...
...And 3 more matches
SVGStringList - Web APIs
defines a list of domstring objects. an svgstringlist object can be designated as read only, which means that attempts to modify the object will result in an exception being thrown. ...
...cation_allowed_err is raised when the list corresponds to a read only attribute or when the object itself is read only. initialize(in domstring newitem) domstring clears all existing current items from the list and re-initializes the list to hold the single item specified by the parameter. if the inserted item is already in a list, it is removed from its previous list before it is inserted into this list. the inserted item is the item itself and not a copy. the return value is the item inserted into the list. exceptions: a domexception with code no_modification_allowed_err is raised when the list corresponds to a read only attribute or when the object itself is read only. getitem(in unsigned long index) domstring returns t...
...eturns the specified item from the list. the returned item is the item itself and not a copy. any changes made to the item are immediately reflected in the list. the first item is number 0. exceptions: a domexception with code no_modification_allowed_err is raised when the list corresponds to a read only attribute or when the object itself is read only. insertitembefore(in domstring newitem, in unsigned long index) domstring inserts a new item into the list at the specified position. the first item is number 0. if newitem is already in a list, it is removed from its previous list before it is inserted into this list. the inserted item is the item itself and not a copy. if the item is already in this list, note that the index of the item to insert befo...
...And 3 more matches
Writing WebSocket servers - Web APIs
programming experience. depending on language support, knowledge of tcp sockets 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 bl...
...ses, but if it chooses any port other than 80 or 443, it may have problems with firewalls and/or proxies. browsers generally require a secure connection for websockets, although they may offer an exception for local devices. the handshake is the "web" in websockets. it's the bridge from http to websockets. in the handshake, details of the connection are negotiated, and either party can back out before completion if the terms are unfavorable. the server must be careful to understand everything the client asks for, otherwise security issues can occur. tip: the request-uri (/chat here) has no defined meaning in the spec. so, many people use it to let one server handle multiple websocket applications. for example, example.com/chat could invoke a multiuser chat app, while /game on the same serve...
...ed (browsers do not display it). if the server doesn't understand that version of websockets, it should send a sec-websocket-version header back that contains the version(s) it does understand. in the example above, it indicates version 13 of the websocket protocol. the most interesting header here is sec-websocket-key. let's look at that next. note: regular http status codes can be used only before the handshake. after the handshake succeeds, you have to use a different set of codes (defined in section 7.4 of the spec). server handshake response when the server receives the handshake request, it should send back a special response that indicates that the protocol will be changing from http to websocket. that header looks something like the following (remember each header line ends with \...
...And 3 more matches
Rendering and the WebXR frame animation callback - Web APIs
an xrsession created to represent an ongoing xr environment session, you need to provide frames of the scene to the xr device for rendering. this article covers the process of driving the frames of the xr scene to the device in the rendering loop, using the xrsession to obtain an xrframe object representing each frame, which is then used to prepare the framebuffer for delivery to the xr device. before you can render the virtual environment, you need to establish a webxr session by creating an xrsession using the navigator.xr.requestsession() method; you also need to associate the session with a framebuffer and perform other setup tasks. these setup tasks are described in the article setting up and shutting down a webxr session. preparing the renderer once the xr session has been set up, with...
...fresh boundary, you can wind up with a tearing effect. tearing occurs when the the display hardware starts the next refresh cycle while the previous frame is still being drawn to the screen. as a result, you wind up with the visual effect of the top part of the screen showing the new frame, while the bottom part of the frame shows some combination of the previous frame and possibly even the frame before that one. your mission, then, is to keep your code tight and lightweight enough that you don't overrrun the time available to you or otherwise cause dropped frames or excessively abuse the main thread. for these reasons, unless your renderer is fairly small and lightweight, with little to do, you should consider offloading everything you can to a worker so you can be computing the next frame wh...
...ou don't overrrun the time available to you or otherwise cause dropped frames or excessively abuse the main thread. for these reasons, unless your renderer is fairly small and lightweight, with little to do, you should consider offloading everything you can to a worker so you can be computing the next frame while the browser handles other things. by simply having your computations and data ready before the frame is actually called for, you can make your site or app render much more efficiently, improving main thread performance and generally making the user experience better. fortunately, there are some tricks you can use to further reduce your impact and optimize performance if your renderering needs are particularly heavy. see the webxr performance guide for recommendations and tips that wil...
...And 3 more matches
Cognitive accessibility - Accessibility
people with cognitive disabilities may require more time to read content, or to perform functions such as filling out forms. solutions include providing users enough additional time to complete tasks or eliminate time constraints altogether. timers options for adjusting time requirements include: allowing the user to turn off or adjust the time to at least 10 times the original limit before encountering it. alerting the user and providing a buffer of at least 20 seconds to extend the timeout duration by a factor of 10 with a simple action, such as hitting the space bar. provide a toggle on content that allows users to enable a longer session time limit, or no session time limit at all. examples of timed content include forms, timed reading exercises, and training materials. if t...
... updates by providing a way to request content updates rather than updating automatically. also, enable a way to make nonessential alerts optional. ensure that people can continue an activity without loss of data after re-authenticating an expired session, for example, saving the state of a questionnaire. make sure to save data in such a way that it can be modified after a user re-authenticates. before re-authenticating, encode the data as hidden or encrypted. providing warnings about inactivity that could result in data loss. when a timeout is used, tell people exactly how much time will cause the session to time out and result in lost data. the exception to this is preserving data for more than 20 hours when no actions are taken. navigation guideline 2.4 states "provide ways to help users...
...fuse users with cognitive disabilities, and should therefore only occur when it is clear that such a change will happen in response to the user's action. changing state should require intentional user action. examples of this are checking a checkbox, entering data or changing a select option. also be sure to provide a submit button to initiate the change of context, and describe what will happen before the change is made. keep navigation consistent throughout the site keep the navigation order consistent between pages. for example, if you have a navigation bar on multiple pages, make that navigation uniform across the site with the same links in the same location. this doesn't just apply to navigation: present all repeated components in the same relative order each time they appear. ...
...And 3 more matches
Implementing a Microsoft Active Accessibility (MSAA) Server - Accessibility
ly need to support msaa on the non-standard controls in your app. so, it's not too bad. mostly myth: microsoft is abandoning msaa in longhorn reality: microsoft's accessibility strategy is changing to a new api in longhorn. msaa will still be supported through an emulation layer, but that will probably be a very slow solution. we'll have to wait and see how good the msaa support in longhorn is, before we can call this one. msaa decision-making guide use msaa whenever you have created custom controls where you're handling the drawing, mouse and keyboard accessibility in your own code. msaa is the only way to let all at's know what your code is doing. don't use msaa if you're not running on a windows platform ... hope that one was obvious. don't use msaa if you're only windows target fo...
...d_sizegrip objid_sound objid_sysmenu objid_titlebar objid_vscroll objid_window [important, but implemented automatically by microsoft windows. will return object of type role_window. see windowfromaccessibleobject quirk explanation below.] dealing with the quirks of msaa msaa has a well deseved reputation for quirkiness. it is not "plug and play", and will take a lot of testing/refinement before your solution works with any product. here are some of it's quirks and some solutions/workarounds: msaa can be crash prone problem: many of msaa's crash occur because more than one process is refcounting the same objects, and because pointers are being shared between processes. when your application closes, different signals are typically broadcast. for example, the application window closes an...
...ive technology will use one of these signals to release the objects of yours that is is refcounting. this can lead to crashes where it releases something and the wrong time, when some of your dll's are unloaded but not others, and a destructor is called in an unloaded dll. solution: create a "shutdown" method for each internal accessible object, to remove any references to other internal objects before any of your dll's are unloaded. in order to do this effectively, you will have to keep track of every accessible object that you create. the shutdown method for an accessibility object should be called whenever the document or ui object it refers to goes away. the easiest way to do that is to keep a pointer to an accessible in each internal ui object. if that pointer is non-null, then there is an...
...And 3 more matches
Linear-gradient Generator - CSS: Cascading Style Sheets
0, 0%, 100%) 0%, hsla(0, 0%, 100%, 0) 50%, hsla(0, 0%, 0%, 0) 50%, hsl(0, 0%, 0%) 100%), -o-linear-gradient(left, hsl(0, 0%, 50%) 0%, hsla(0, 0%, 50%, 0) 100%); background-color: #f00; } .ui-color-picker .picker { width: 10px; height: 10px; margin: -5px 0 0 -5px; border-radius: 50%; border: 1px solid #fff; position: absolute; top: 45%; left: 45%; } .ui-color-picker .picker:before { width: 8px; height: 8px; content: ""; position: absolute; border: 1px solid #999; border-radius: 50%; } .ui-color-picker .hue, .ui-color-picker .alpha { width: 198px; height: 28px; margin: 5px; border: 1px solid #fff; float: left; } .ui-color-picker .hue { background: url("images/hue_mask.png"); background: -moz-linear-gradient(left, #f00 0%, #ff0 16.66%, #0f0 33.33%, #0ff 50%, ...
...c="hexa"] > input { width: 90px; height: 24px; padding: 2px 0; -moz-box-sizing: border-box; -webkit-box-sizing: border-box; box-sizing: border-box; } /* preview color */ .ui-color-picker .preview { width: 95px; height: 53px; margin: 5px; margin-top: 10px; border: 1px solid #ddd; background-image: url("images/alpha.png"); float: left; position: relative; } .ui-color-picker .preview:before { height: 100%; width: 50%; left: 50%; top: 0; content: ""; background: #fff; position: absolute; z-index: 1; } .ui-color-picker .preview-color { width: 100%; height: 100%; background-color: rgba(255, 0, 0, 0.5); position: absolute; z-index: 1; } .ui-color-picker .switch_mode { width: 10px; height: 20px; position: relative; border-radius: 5px 0 0 5px; border: 1px solid #ddd; ...
...rue'] { opacity: 1; z-index: 1; } .gradient-axis:after { content: ""; width: 25px; height: 100%; background-color: #ccc; position: absolute; left: 0; top: 0; } .gradient-axis .gradient-line { width: 80%; height: 100%; margin: 0px auto; position: relative; } .gradient-axis .gradient-line:hover { cursor: pointer; } .gradient-axis .gradient-line:after, .gradient-axis .gradient-line:before { content: ""; width: 1px; height: 100px; background-color: #ccc; position: absolute; top: -48px; } .gradient-axis .gradient-line:after { left: -1px; } .gradient-axis .gradient-line:before { right: -1px; } .gradient-axis .gradient-point { width: 16px; height: 16px; margin: 0 0 0 -8px; top: -7px; border-radius: 50%; background-color: #fff; border: 1px solid #999; position: absol...
...And 3 more matches
Expressions and operators - JavaScript
mation about operator precedence. assignment operators comparison operators arithmetic operators bitwise operators logical operators string operators conditional (ternary) operator comma operator unary operators relational operators javascript has both binary and unary operators, and one special ternary operator, the conditional operator. a binary operator requires two operands, one before the operator and one after the operator: operand1 operator operand2 for example, 3+4 or x*y. a unary operator requires a single operand, either before or after the operator: operator operand or operand operator for 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...
... that means that (x = y) returns y, (x += y) returns the resulting sum x + y, (x **= y) returns the resulting power x ** y, and so on. in the case of logical assignments, (x &&= y), (x ||= y), and (x ??= y), the return value is that of the logical operation without the assignment, so x && y, x || y, and x ?? y, respectively. note that the return values are always based on the operands’ values before the operation. when chaining these expressions, each assignment is evaluated right-to-left. consider these examples: w = z = x = y is equivalent to w = (z = (x = y)) or x = y; z = y; w = y z += x *= y is equivalent to z += (x *= y) or tmp = x * y; x *= y; z += tmp (except without the tmp). destructuring for more complex assignments, the destructuring assignment syntax is a javascript expr...
...e not of the same type, javascript attempts to convert them to an appropriate type for the comparison. this behavior generally results in comparing the operands numerically. the sole exceptions to type conversion within comparisons involve the === and !== operators, which perform strict equality and inequality comparisons. these operators do not attempt to convert the operands to compatible types before checking equality. the following table describes the comparison operators in terms of this sample code: var var1 = 3; var var2 = 4; comparison operators operator description examples returning true equal (==) returns true if the operands are equal. 3 == var1 "3" == var1 3 == '3' not equal (!=) returns true if the operands are not equal. ...
...And 3 more matches
Object.create() - JavaScript
object.create() will result in an empty array being returned. var obj = object.create({ a: 1, b: 2 }); > console.log(object.entries(obj)); // shows "[]" some non-solutions a good solution for the missing object-methods is not immediately apparent. ...
...object-method > ocn.tostring() // error: function.prototype.tostring requires that 'this' be a function adding the missing object-method directly to new object's "prototype" does not work either, since the new object does not have a real prototype (which is really the cause of all these problems) and one cannot be directly added: ocn = object.create( null ); // create "null" object (same as before) ocn.prototype.tostring = object.tostring; // error: cannot set property 'tostring' of undefined ocn.prototype = {}; // try to create a prototype ocn.prototype.tostring = object.tostring; // since new object lacks method then try assigning it from standard-object > ocn.tostring() // error: ocn.tostring is not a function adding the missing object-method by using the ...
...however, adding the generic method directly, does: ocn = object.create( null ); // create "null" object (sa...
...And 3 more matches
String.prototype.localeCompare() - 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. the new locales and options arguments let applications specify the language whose sort order should be used and customize the behavior of the function. in older implementations, which ignore the locales and options arguments, the locale and sort order used are entirely implementation-dependent. ...
...tion and let applications specify the language whose formatting conventions should be used. in implementations which ignore the locales and options arguments, the locale used and the form of the string returned are entirely implementation-dependent. see the intl.collator() constructor for details on these parameters and how to use them. ...
...he form of the string returned are entirely implementation-dependent. see the intl.collator() constructor for details on these parameters and how to use them. return value a negative number if referencestr occurs before comparestring; positive if the referencestr occurs after comparestring; 0 if they are equivalent. description returns an integer indicating whether the referencestr comes before, after or is equivalent to the comparestring. ...
...And 3 more matches
Strict mode - JavaScript
ents enclosed in {} braces; attempting to apply it to such contexts does nothing. eval code, function code, event handler attributes, strings passed to windowtimers.settimeout(), and related functions are entire scripts, and invoking strict mode in them works as expected. strict mode for scripts to invoke strict mode for an entire script, put the exact statement "use strict"; (or 'use strict';) before any other statements. // whole-script strict mode syntax 'use strict'; var v = "hi! i'm a strict mode script!"; this syntax has a trap that has already bitten a major site: it isn't possible to blindly concatenate conflicting scripts. consider concatenating a strict mode script with a non-strict mode script: the entire concatenation looks strict! the inverse is also true: non-strict plus stric...
...of wrapping the entire contents of a script in a function and having that outer function use strict mode. this eliminates the concatenation problem and it means that you have to explicitly export any shared variables out of the function scope. strict mode for functions likewise, to invoke strict mode for a function, put the exact statement "use strict"; (or 'use strict';) in the function's body before any other statements. function strict() { // function-level strict mode syntax 'use strict'; function nested() { return 'and so am i!'; } return "hi! i'm a strict mode function! " + nested(); } function notstrict() { return "i'm not strict."; } strict mode for modules ecmascript 2015 introduced javascript modules and therefore a 3rd way to enter strict mode. the entire contents of ...
...the normal code may duplicate property names, with the last one determining the property's value. but since only the last one does anything, the duplication is simply a vector for bugs, if...
...And 3 more matches
Navigation and resource timings - Web Performance
al resource, the value will be the same as performancetiming.fetchstart. domainlookupstart when the domain lookup starts. if a persistent connection is used, or the information is stored in a cache or a local resource, the value will be the same as performancetiming.fetchstart. fetchstart when the browser is ready to fetch the document using an http request. this moment is before the check to any application cache. requeststart when the browser sent the request to obtain the actual document, from the server or from a cache. if the transport layer fails after the start of the request and the connection is reopened, this property will be set to the time corresponding to the new request. responsestart when the browser received the first byte of the re...
...ishes. if there is no previous document, or if the previous document, or one of the needed redirects, is not of the same origin, the value returned is 0. dominteractive when the parser finished its work on the main document, that is when its document.readystate changes to 'interactive' and the corresponding readystatechange event is thrown. domcontentloadedeventstart right before the parser sent the domcontentloaded event, that is right after all the scripts that need to be executed right after parsing have been executed. domcontentloadedeventend right after all the scripts that need to be executed as soon as possible, in order or not, have been executed. domcomplete when the parser finished its work on the main document, that is when its document.
...e for first-paint and first-contentful-paint. we use performance.getentriesbytype('navigation') and performance.getentriesbytype('resource') to query the navigation and resource timings respectively. navigation timing when a user requests a web site or application, to populate the browser the user agent goes through a series of steps, including a dns lookup, tcp handshake, and ssl negotiation, before the user agent makes the actual request and the servers return the requested assets. the browser then parses the content received, builds the dom, cssom, accessibility, and render trees, eventually rendering the page. once the user agent stops parsing the document, the user agent sets the document readiness to interactive. if there are deferred scripts needing to be parsed, it will do so, then fi...
...And 3 more matches
Understanding WebAssembly text format - WebAssembly
local.get 2) the instruction local.get 0 would get the i32 parameter, local.get 1 would get the f32 parameter, and local.get 2 would get the f64 local. ...
...ems simply by including a name prefixed by a dollar symbol ($) just before the type declaration. thus you could rewrite our previous signature like so: (func (param $p1 i32) (param $p2 f32) (local $loc f64) …) and then could write local.get $p1 instead of local.get 0, etc. (note that when this text gets converted to binary, though, the binary will contain only the integer.) stack machines before we can write a function body, we have to talk about one more thing: stack machines. although the browser compiles it to something more efficient, wasm execution is defined in terms of a stack machine where the basic idea is that every type of instruction pushes and/or pops a certain number of i32/i64/f32/f64 values to/from a stack. for example, local.get is defined to push the value of the local...
...alue — the result of the expression ($p + $p), which is handled by i32.add. the return value of a function is just the final value left on the stack. the webassembly validation rules ensure the stack matches exactly: if you declare a (result f32), then the stack must contain exactly one f32 at the end. if there is no result type, the stack must be empty. our first function body as mentioned before, the function body is simply a list of instructions that are followed as the function is called. putting this together with what we have already learned, we can finally define a module containing our own simple function: (module (func (param $lhs i32) (param $rhs i32) (result i32) local.get $lhs local.get $rhs i32.add)) this function gets two parameters, adds them together, and re...
...And 3 more matches
Using the WebAssembly JavaScript API - WebAssembly
two instead can work together, drawing on each other’s strengths. loading our wasm module without streaming if you can't or don't want to use the streaming methods as described above, you can use the non-streaming methods webassembly.compile / webassembly.instantiate instead. these methods don't directly access the byte code, so require an extra step to turn the response into an arraybuffer before compiling/instantiating the wasm module. the equivalent code would look like this: fetch('simple.wasm').then(response => response.arraybuffer() ).then(bytes => webassembly.instantiate(bytes, importobject) ).then(results => { results.instance.exports.exported_func(); }); viewing wasm in developer tools in firefox 54+, the developer tool debugger panel has functionality to expose the text...
...a memory export (via instance.prototype.exports). more involved memory example let’s make the above assertions clearer by looking at a more involved memory example — a webassembly module that imports the memory instance we defined earlier, populates it with an array of integers, then sums them. you can find this at memory.wasm. make a local copy of memory.wasm in the same directory as before. ...
...dule that imports the memory instance we defined earlier, populates it with an array of integers, then sums them. you can find this at memory.wasm. make a local copy of memory.wasm in the same directory as before. note: you can see the module’s text representation at memory.wat. ...
...And 3 more matches
Intercepting Page Loads - Archive of obsolete content
f the loaded page, just like you normally would for xul and html documents. you can't, however, easily cancel the page load. you can close the tab, redirect the tab to about:blank or another page, or tell the browser to stop loading this page, but in general you don't want to do this because it will be visible to the user and it will look like a bug. there are better ways to intercept page loads before any content is downloaded, and before the user sees anything in the tab. http observers another common way of detecting and intercepting loads is using http observer topics. this is how the tamper data extension and others do it. http notifications are fired for all http requests originating from firefox. they are window-independent, so it is better to keep your observer code in non-chrome obj...
...results.ns_binding_aborted); } } } this example shows how you can obtain the url for the request, analyze it using regular expressions, and perform actions on it such as modifying http headers, or even canceling the request. http observers are great for load detection, and filtering by url. you can also use these in conjunction with nsitraceablechannel to get and modify the response text before it gets to the original requester. you won't be able to make dom modifications like with the load events, since these notifications are triggered before the response arrives and is parsed into dom tree, so this is not the best approach for the typical greasemonkey-style extensions. notes on usage: efficiency is very important when adding http observers. remember that your observe method will b...
...f the first things we do is check if the url is of interest to us, otherwise we let it go. avoid heavy, time-consuming operations, or the user's browsing experience will become exasperating. . you have to take into account that a page load may involve several http requests, specially when redirects are involved. if you enter gmail.com in your browser, you will probably be redirected a few times before reaching the page that actually displays any content. all of these "hops" will involve a call to your observer. . the aforementioned observer notifications page has more information about these notifications and links to other useful documentation. webprogresslisteners when used in the chrome, this is a more sophisticated way of intercepting and modifying the various stages in page loads. but...
...And 2 more matches
The Essentials of an Extension - Archive of obsolete content
notation, and they're just common practice. as long as your id has some uniqueness to it, it's ok to use either form. <em:name>xul school hello world</em:name> <em:description>welcome to xul school!</em:description> <em:version>0.1</em:version> <em:creator>appcoast</em:creator> <em:homepageurl>https://developer.mozilla.org/docs/xul_school</em:homepageurl> this is the data that is displayed before and after the extension is 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...
...tml, so you'll see many similarities between the two. however, xul is also an improvement over html, having learned from many of the mistakes made during the evolution of html. xul allows you to create richer and more interactive interfaces than the ones you can create with html, or at least xul makes it easier. xul files usually define one of two things: windows or overlays. the file you opened before, downloads.xul, has the code that defines the downloads window. the xul file included in the hello world extension is an overlay. an overlay extends an existing window, adding new elements to it or replacing some of the elements in it. the line that we skipped in the chrome.manifest file states that this xul file is an overlay for the main browser window: overlay chrome://browser/content/brows...
..., it is recommended that you add it there. otherwise, the root menu might be your only recourse. ...
...And 2 more matches
MCD, Mission Control Desktop, AKA AutoConfig - Archive of obsolete content
var ldaphost = "example.com"; var ldapbase = "dc=company,dc=local"; if( userinfo.envuser ) { var ldapfilter = "samaccountname=" + userinfo.envuser; } else { throw("couldn't get uid from the environment"); } // ldap attributes to retrieve from the server var ldapattrs = new array( "cn", "mail", "samaccountname" ); // add more attributes here, if needed) // define how to process ldap results before we make the call function processldapvalues(queryresults) { if( queryresults ) { // build the userinfo object for later use for( var attr in ldapattrs ) { userinfo[ ldapattrs[attr] ] = getldapvalue( queryresults, ldapattrs[attr] ); } } else { throw( "no ldap results" ); } } // call upon ldap for the values in ldapattrs array, // uses the previous processldapvalues() ge...
...lockpref("mail.server.server3.type", "nntp"); lockpref("mail.server.server3.username", env_user); //call to ldap to get user's attribute. getldapattributes("ldap2.int-evry.fr", "ou=people,dc=int-evry,dc=fr", "uid=" +env_user, "uid,cn,mail"); } catch(e) { displayerror("lockedpref", e); } eop print $page; windows peculiarities without web base cgi file, beware that in windows, the original (before encoding) mozilla.js file must start with: //begin ce prefs , if not you'll get "failed to read configuration file..." message, and mozilla won't start :-( in windows environment variables like user or home, are username and homepath, that's why we must create a different pair of configuration files (cfg and cgi) for both systems (linux/windows). perhaps there's a way in javascript to detect ope...
... allows users to use a single javascript for both systems (linux and windows) with a subtle if... else test on environment variables. ldap fail-over creating an array of possible running ldap servers permits an ldap fail-over, then a shuffle function allows us to randomly pick up a running ldap server. ...
...And 2 more matches
Migrate apps from Internet Explorer to Mozilla - Archive of obsolete content
introduction when netscape started the mozilla browser, it made the conscious decision to support w3c standards. as a result, mozilla is not fully backwards-compatible with netscape navigator 4.x and microsoft internet explorer legacy code; for example, mozilla does not support <layer> as i will discuss later. browsers, like internet explorer 4, that were built before the conception of w3c standards inherited many quirks. in this article, i will describe mozilla's quirks mode, which provides strong backwards html compatibility with internet explorer and other legacy browsers. i'll also cover nonstandard technologies, such as xmlhttprequest and rich text editing, that mozilla does support because no w3c equivalent existed at the time. they include: html 4.01, xhtml 1.0 and xhtml 1.1 ...
...access protocol: soap 1.1 ecma-262, revision 3 (javascript 1.5): ecma-262 general cross-browser coding tips even though web standards do exist, different browsers behave differently (in fact, the same browser may behave differently depending on the platform). many browsers, such as internet explorer, also support pre-w3c apis and have never added extensive support for the w3c-compliant ones. before i go into the differences between mozilla and internet explorer, i'll cover some basic ways you can make a web application extensible in order to add new browser support later. since different browsers sometimes use different apis for the same functionality, you can often find multiple if() else() blocks throughout the code to differentiate between the browsers. the following code shows blocks d...
...akes a copy of the node it is called on and returns the copy. if adeep is true, it copies over the node's entire subtree. createelement( atagname ) creates and returns a new and parentless dom node of the type specified by atagname. createtextnode( atextvalue ) creates and returns a new and parentless dom textnode with the data value specified by atextvalue. insertbefore( anewnode, achildnode ) inserts anewnode before achildnode, which must be a child of the current node. removechild( achildnode ) removes achildnode and returns a reference to it. replacechild( anewnode, achildnode ) replaces achildnode with anewnode and returns a reference to the removed node. document fragments for performance reasons, you can create documents ...
...And 2 more matches
Dynamically modifying XUL-based user interface - Archive of obsolete content
iframe>, <browser>, or a <tabbrowser> element. you must be sure to always manipulate the correct document. (read more about this in working with windows in chrome code.) when your script is included using a <script> tag, the document property references the dom document that includes the script. examples: using dom methods this section demonstrates the use of appendchild(), createelement(), insertbefore(), and removechild() dom methods. removing all children of an element this example removes all children of an element with id=someelement from the current document, by calling removechild() method to remove the first child, until there are no children remaining. note, that haschildnodes() and firstchild are also part of the dom api. var element = document.getelementbyid("someelement"); while(el...
...that haschildnodes() and firstchild are also part of the dom api. var element = document.getelementbyid("someelement"); while(element.haschildnodes()){ element.removechild(element.firstchild); } inserting menu items to a menu this example adds two new menu items to a <menupopup>: to the start and to the end of it. ...
...thod to create the items, and insertbefore() with appendchild() to insert the created xml elements within the document. note: document.createelementns() creates an element, but does not put it anywhere in the document. you need to use other dom methods, such as appendchild() to insert the newly created element in the document. appendchild() appends the node after all other nodes, while insertbefore() inserts the node before the node referenced by its second parameter. function createmenuitem(alabel) { const xul_ns = "http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"; var item = document.createelementns(xul_ns, "menuitem"); // create a new xul menuitem item.setattribute("label", alabel); return item; } var popup = document.getelementbyid("mypopup"); // a <menupopup> ele...
...And 2 more matches
Static Content - Archive of obsolete content
one interesting thing about this example is that only one menupopup will be created, even...
...tion> <menupopup> <menuitem uri="?country" label="?countrytitle" value="?country"/> </menupopup> </action> </template> </menulist> the only difference between the previous example and this one is that the menulist element has some additional content added before the template. the content will be displayed just like it would be as if the template wasn't present. that is, before the template is examined, the menulist would have one item in it, with the label 'all'. the template generates two results as before, one for each country, and appends a menuitem for each one. one interesting thing about this example is that only one menupopup will be created, even though there are two in the code, one outside the template and another one inside the action body. this demonstrates...
...dy present as long as some element with the same tag name exists. if you were to change the static content to be some other element besides a menupopup, it won't match, so the builder will create a new one when handling the action. this becomes useful when using multiple rules and we'll see some examples of this later. here is the example to try. ...
...And 2 more matches
Tree Widget Changes - Archive of obsolete content
sort column, and position and size info about the columns. for the most part these objects are readonly; you can modify the columns by just adjusting the treecol attributes directly. the tree and view methods no longer take ids as arguments when columns are used. instead, they use nsitreecolumns. for example, nsitreeview.getcellvalue() takes a row index and a nsitreecolumn as arguments, whereas before it took a row index and a column id. to get a column in javascript: tree.columns.getcolumnfor(treecolelement); tree.columns.getnamedcolumn(treecolid); tree.columns.getcolumnat(index); you can also just use array syntax to get a column: tree.columns["lastname"]; tree.columns[5]; once you have a column, you can get various properties of it: column.index - the index of the column in displa...
... the column column.width - the width of the column in c++ code, you can also get the atom attribute of nsitreecolumn which returns an nsiatom for the column, making it fast to do comparisons. nscomptr<nsiatom> atom; acol->getatom(getter_addrefs(atom)); if (atom = kmycol) ... one feature that has been added is restorenaturalorder which may be used to restore the original order of the columns before the user moved them around. tree.columns.restorenaturalorder() there is also a command on the end of the tree's column picker which the user may use to restore the original column order. this will be hidden if the column redordering is disabled using enablecolumndrag="false". some specific changes you should now get the tree selection object from the view, not the box object, meaning use tre...
...validatecell(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. ...
...And 2 more matches
panel - Archive of obsolete content
Archive › Mozilla › XUL › panel
noautohide type: boolean if false, the default value, the panel will be hidden when the user clicks outside the panel or switches focus to another application. if true, the panel will only be closed when the hidepopup method is called. norestorefocus type: boolean if false, the default value, then when the panel is hidden, the keyboard focus will be restored to whatever had the focus before the panel was opened. if true, the focus will not be reset, although it will be cleared if the focus is within the panel. onpopuphidden type: script code this event is sent to a popup after it has been hidden. this event may also be received while the popup is still open, but when sub-menus contained within this popup are hidden. example: <menupopup id="top" onpopuphidden="consol...
...enu id="submenu2" label="submenu 1"> <menupopup id="submenu2-popup"> <menuitem label="submenu2 item 1"/> <menuitem label="submenu2 item 2"/> </menupopup> </menu> <menupopup/> onpopuphiding type: script code this event is sent to a popup when it is about to be hidden. onpopupshowing type: script code this event is sent to a popup just before it is opened. this handler is usually used to dynamically set the contents when the user requests to display it. returning false from this event handler prevents the popup from appearing. onpopupshown type: script code this event is sent to a popup after it has been opened, much like the onload event is sent to a window when it is opened. position type: string the position attri...
... second word). the anchor value (ie, the first word) can be one of topleft, topright, bottomleft, bottomright, leftcenter, rightcenter, topcenter or bottomcenter. the popup value (ie, the second word) can be one of topleft, topright, bottomleft or bottomright. positions specified as a single word string are shortcuts for the values above. valid single-word values are after_start, after_end, before_start, before_end, end_after, end_before, start_after, start_before, overlap, at_pointer or after_pointer. for more details, including examples, please see popup positioning titlebar type: string set the panel's titlebar attribute to the value normal to display a panel with a titlebar. the noautohide attribute must be set to true. top type: integer overrides the vertical positio...
...And 2 more matches
Using IO Timeout And Interrupt On NT - Archive of obsolete content
ing netscape portable runtime's (nspr) io timeout and interrupt on windows nt 3.51 and 4.0. ...
...if the thread gets interrupted by another thread's <tt>pr_interrupt()</tt> call, the io function returns with <tt>pr_pending_interrupt_error</tt>. on windows nt, nspr io is implemented using nt's overlapped (also called asynchronous) io. ...
...reads) monitoring the io completion port for completed io requests. if a completed io request appears at the io completion port, an idle thread fetches it and wakes up the thread that issued the io request earlier. this is the normal way the thread is awakened. io timeout and interrupt however, nspr may wake up the thread in two other situations: if the overlapped io request is not completed before the specified timeout. (note that we can't specify timeout on overlapped io requests, so the timeouts are all handled at the nspr level.) in this case, the error is <tt>pr_io_timeout_error</tt>. if the thread gets interrupted by another thread's <tt>pr_interrupt()</tt> call. in this case, the error is <tt>pr_pending_interrupt_error</tt>. these two errors are generated by the nspr layer, so the ...
...And 2 more matches
Cascade and inheritance - Learn web development
city, and inheritance — which control how css is applied to html and how conflicts are resolved. while working through this lesson may seem less immediately relevant and a little more academic than some other parts of the course, an understanding of these things will save you much pain later on! we encourage you to work through this section carefully, and check that you understand the concepts before moving on. 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 cascade and specificity, and how inheritance works in css. conflicting rules css stands for cascading style sheets, and that...
...the <a> element — for example a { color: red; }? resetting all property values the css shorthand property all can be used to apply one of these inheritance values to (almost) all properties at once. its value can be any one of the inheritance values (inherit, initial, unset, or revert). it's a convenient way to undo changes made to styles so that you can get back to a known starting point before beginning new changes. in the below example we have two blockquotes. the first has styling applied to the blockquote element itself, the second has a class applied to the blockquote which sets the value of all to unset. try setting the value of all to some of the other available values and observe what the difference is. understanding the cascade we now understand why a paragraph nested de...
... the first two selectors are competing over the styling of the link's background color — the second one wins and makes the background color blue ...
...And 2 more matches
Tips for authoring fast-loading HTML pages - Learn web development
ending 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 last modified time of the referenced files can delay the initial display of the web page, since the browser must check the modification time for each of these files, before rendering the page. if you use background images a lot in your css, you can reduce the number of http lookups needed by combining the images into one, known as an image sprite. then you just apply the same image each time you need it for a background and adjust the x/y coordinates appropriately. this technique works best with elements that will have limited dimensions, and will not work for ever...
...e download page content first, along with any css or javascript that may be required for its initial display, so that the user gets the quickest apparent response during the page loading. this content is typically text, and can, therefore, benefit from text compression in transit, thus providing an even quicker response to the user. any dynamic features that require the page to complete loading before being used, should be initially disabled, and then only enabled after the page has loaded. this will cause the javascript to be loaded after the page contents, which will improve the overall appearance of the page load. reduce the number of inline scripts inline scripts can be expensive for page loading since the parser must assume that an inline script could modify the page structure while par...
...</table> see also: css flexible box layout and css grid layout specifications. minify and compress svg assets svg produced by most drawing applications often contains unnecessary metadata which can be removed. configure your servers, apply gzip compression for svg assets. minify and compress your images large images cause your page to take more time to load. consider compressing your images before adding them to your page, using compression features built into image-manipulation tools such as photoshop, or using a specialized tool such as compress jpeg or tiny png,. specify sizes for images and tables if the browser can immediately determine the height and/or width of your images and tables, it will be able to display a web page without having to reflow the content. this not only speeds ...
...And 2 more matches
Video and audio content - Learn web development
is for controlling them. we'll not be looking at javascript here — just the basic foundations that can be achieved with html. we won't be teaching you how to produce audio and video files — that requires a completely different skillset. we have provided you with sample audio and video files and example code for your own experimentation, in case you are unable to get hold of your own. note: before you begin here, you should also know that there are quite a few ovps (online video providers) like youtube, dailymotion, and vimeo, and online audio providers like soundcloud. such companies offer a convenient, 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...
...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, while video tracks are encoded using (as you probably have guessed) a video codec. as we talked about before, different browsers support different video and audio formats, and different container formats (like mp3, mp4, and webm, which in turn can contain different types of video and audio). for example: a webm container typically packages vorbis or opus audio with vp8/vp9 video. this is supported in all modern browsers, though older versions may not work. an mp4 container often packages aac or mp3...
...t of the page is loading. you are advised not to use autoplaying video (or audio) on your sites, because users can find it really annoying. loop makes the video (or audio) start playing again whenever it finishes. this can also be annoying, so only use if really necessary. muted causes the media to play with the sound turned off by default. poster the url of an image which will be displayed before the video is played. it is intended to be used for a splash screen or advertising screen. preload used for buffering large files; it can take one of three values: "none" does not buffer the file "auto" buffers the media file "metadata" buffers only the metadata for the file you can find the above example available to play live on github (also see the source code.) note that we ...
...And 2 more matches
Choosing the right approach - Learn web development
cks settimeout() settimeout() is a method that allows you to run a function after an arbitrary amount of time has passed. useful for... single delayed operation repeating operation multiple sequential operations multiple simultaneous operations yes yes (recursive timeouts) yes (nested timeouts) no code example here the browser will wait two seconds before executing the anonymous function, then will display the alert message (see it running live, and see the source code): let mygreeting = settimeout(function() { alert('hello, mr. universe!'); }, 2000) pitfalls you can use recursive settimeout() calls to run a function repeatedly in a similar fashion to setinterval(), using code like this: let i = 1; settimeout(function run() { console.log(i...
...the interval will be the same regardless of how long the code takes to run. with setinterval(), the interval we choose includes the time taken to execute the code we want to run in. let's say that the code takes 40 milliseconds to run — the interval then ends up being only 60 milliseconds. when your code has the potential to take longer to run than the time interval you’ve a...
...otes.requires a vendor prefix or different name for use.requires a vendor prefix or different name for use. further information cooperative asynchronous javascript: timeouts and intervals, in particular requestanimationframe() requestanimationframe() reference promises promises are a javascript feature that allows you to run asynchronous operations and wait until it is definitely complete before running another operation based on its result. promises are the backbone of modern asynchronous javascript. useful for... single delayed operation repeating operation multiple sequential operations multiple simultaneous operations no no yes see promise.all(), below code example the following code fetches an image from the server and displays it inside...
...And 2 more matches
Arrays - Learn web development
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 strings. for example: let sequence = [1, 1, 2, 3, 5, 8, 13]; let random = ['tree', 795, [0, 1, 2]]; before proceeding, create a few example arrays. accessing and modifying array items you can then access individual items in the array using bracket notation, in the same way that you accessed the letters in a string. enter the following into your console: shopping[0]; // returns "bread" you can also modify an item in an array by simply giving a single array item a new value. try this: shopp...
...sing bracket notation, in the same way that you accessed the letters in a string. enter the following into your console: shopping[0]; // returns "bread" you can also modify an item in an array by simply giving a single array item a new value. try this: shopping[0] = 'tahini'; shopping; // shopping will now return [ "tahini", "milk", "cheese", "hummus", "noodles" ] note: we've said it before, but just as a reminder — computers start counting from 0! note that an array inside an array is called a multidimensional array. you can access an item inside an array that is itself inside another array by chaining two sets of square brackets together. for example, to access one of the items inside the array that is the third item inside the random array (see previous section), we could do...
... is called a multidimensional array. you can access an item inside an array that is itself inside another array by chaining two sets of square brackets together. for example, to access one of the items inside the array that is the third item inside the random array (see previous section), we could do something like this: random[2][2]; try making some more modifications to your array examples before moving on. play around a bit, and see what works and what doesn't. finding the length of an array you can find out the length of an array (how many items are in it) in exactly the same way as you find out the length (in characters) of a string — by using the length property. try the following: shopping.length; // should return 5 this has other uses, but it is most commonly used to tell a l...
...And 2 more matches
Basic math in JavaScript — numbers and operators - Learn web development
te 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 rarely come across a need to start thinking about other types, if ever. the second bit of good news is that unlike some other programming languages, javascript only has one data type for numbers, both i...
... 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 containing numbers before you move on. now let's check that both our original variables are of the same datatype. there is an operator called typeof in javascript that does this. enter the below two lines as shown: typeof myint; typeof myfloat; you should get "number" returned in both cases — this makes things a lot easier for us than if different numbers had different data types, and we had to deal with them in di...
...um2 holds the value 50 and num1 holds the value 10 (as originally stated above): num2 + num1 / 8 + 2; as a human being, you may read this as "50 plus 10 equals 60", then "8 plus 2 equals 10", and finally "60 divided by 10 equals 6". but the browser does "10 divided by 8 equals 1.25", then "50 plus 1.25 plus 2 equals 53.25". this is because of operator precedence — some operators are applied before others when calculating the result of a calculation (referred to as an expression, in programming). operator precedence in javascript is the same as is taught in math classes in school — multiply and divide are always done first, then add and subtract (the calculation is always evaluated from left to right). if you want to override operator precedence, you can put parentheses round the parts ...
...And 2 more matches
Aprender y obtener ayuda - Learn web development
cific subjects, getting into deep problem solving, and improving your mastery of the techniques required — strengthening the neural pathways in your brain where that information is stored. it isn't however very good at getting an understanding of "the big picture", and unlocking new neural pathways when you are trying to understand new subjects or solve new problems that you haven't come across before. for that, you need diffuse thinking. this is the opposite of focus — you let your brain wander around the wider landscape, searching around for connections you didn't have before, touching on new things (or new combinations of things) that you can then focus on later, to strengthen them and start to really understand what they mean. this is why it is usually good to read some introductory m...
... it is also why you can sometimes get really stuck on a problem, but then figure out the answer when you go for a coffee break (or a walk). you might: know how to fix problem a with tool a. know how to fix problem b with tool b. ...
... the room — most people we have are distracted by their phone a lot, so you should leave it somewhere else. take regular breaks. it is not good for your motivation to keep working away for hours with no break, especially if you are finding it hard or getting stuck on a problem. that just leads to frustration — it is often better to take a break, move around for a bit, then relax with a drink before getting back to work, and as we said earlier, the diffuse learning you do in that time can often help you to figure out a solution to the problem you were facing. it is also physically bad to work for too long without a break — looking at a monitor for too long can hurt your eyes, and sitting still for too long can be bad for your back or legs. we'd recommend taking a 15 minutes break every hou...
...And 2 more matches
Website security - Learn web development
d by flooding a target site with fake requests so that access to a site is disrupted for legitimate users. the requests may simply be numerous, or they may individually consume large amounts of resource (e.g., slow reads or uploading of large files). dos defenses usually work by identifying and blocking "bad" traffic while allowing legitimate messages through. these defenses are typically located before or in the web server (they are not part of the web application itself). directory traversal (file and disclosure). in this attack, a malicious user attempts to access parts of the web server file system that they should not be able to access. this vulnerability occurs when the user is able to pass filenames that include file system navigation characters (for example, ../../). the solution is to ...
...server (they are not part of the web application itself). directory traversal (file and disclosure). in this attack, a malicious user attempts to access parts of the web server file system that they should not be able to access. this vulnerability occurs when the user is able to pass filenames that include file system navigation characters (for example, ../../). the solution is to sanitize input before using it. file inclusion. in this attack, a user is able to specify an "unintended" file for display or execution in data passed to the server. when loaded, this file might be executed on the web server or the client-side (leading to an xss attack). the solution is to sanitize input before using it. command injection. command injection attacks allow a malicious user to execute arbitrary system ...
...tended" file for display or execution in data passed to the server. when loaded, this file might be executed on the web server or the client-side (leading to an xss attack). the solution is to sanitize input before using it. command injection. command injection attacks allow a malicious user to execute arbitrary system commands on the host operating system. the solution is to sanitize user input before it might be used in system calls. for a comprehensive listing of website security threats see category: web security exploits (wikipedia) and category: attack (open web application security project). a few key messages almost all of the security exploits in the previous sections are successful when the web application trusts data from the browser. whatever else you do to improve the security ...
...And 2 more matches
Accessibility in React - Learn web development
ove between each of the filter buttons. keep going until the focus indicator is around the first "edit" button. press enter. the <todo /> component will switch templates, as we designed, and you'll see a form that lets us edit the name of the task. but where did our focus indicator go? when we switch between templates in our <todo /> component, we completely remove the elements that were there before to replace them with something else. that means the element that we were focused on vanishes, and nothing is in focus at all. this could confuse a wide variety of users — particularly users who rely on the keyboard, or users who use a screen reader. to improve the experience for keyboard and screen-reader users, we should manage the browser’s focus ourselves. focusing between templates whe...
... editfieldref.current.focus(); } else { editbuttonref.current.focus(); } }, [isediting]); this kind of mostly works. head back to your browser and you’ll see that your focus moves between edit <input> and "edit" button as you start and end an edit. however, you may have noticed a new problem — the "edit" button in the final <todo /> component is focussed immediately on page load, before we even interact with the app! our useeffect() hook is behaving exactly as we designed it: it runs as soon as the component renders, sees that isediting is false, and focuses the "edit" button. because there are three instances of <todo />, we see focus on the last "edit" button. we need to refactor our approach so that focus changes only when isediting changes from one value to another. more ...
...at focus changes only when isediting changes from one value to another. more robust focus management in order to meet our refined criteria, we need to know not just the value of isediting, but also when that value has changed. in order to do that, we need to be able to read the previous value of the isediting constant. using pseudocode, our logic should be something like this: if (wasnoteditingbefore && iseditingnow) { focusoneditfield() } if (waseditingbefore && isnoteditingnow) { focusoneditbutton() } the react team had discussed ways to get a component’s previous state, and has provided an example custom hook we can use for the job. paste the following code near the top of todo.js, above your todo() function. function useprevious(value) { const ref = useref(); useeffect(() => ...
...And 2 more matches
React interactivity: Events and state - Learn web development
ully add and delete tasks, and toggle tasks as completed. prerequisites: familiarity with the core html, css, and javascript languages, knowledge of the terminal/command line. objective: to learn about handling events and state in react, and use those to start making the case study app interactive. handling events if you've only written vanilla javascript before now, you might be used to having a separate javascript file, where you query for some dom nodes and attach listeners to them. for example: const btn = document.queryselector('button'); btn.addeventlistener('click', () => { alert("hi!"); }); in react, we write event handlers directly on the elements in our jsx, like this: <button type="button" onclick={() => alert("hi!")} > say hi! </b...
...bute to the form’s input, and set its value to name. your browser will render "use hooks!" inside the input. <input type="text" id="new-todo-input" classname="input input__lg" name="text" autocomplete="off" value={name} /> change "use hooks!" to an empty string once you're done; this is what we want for our initial state. const [name, setname] = usestate(''); reading user input before we can change the value of name, we need to capture a user's input as they type. for this, we can listen to the onchange event. let’s write a handlechange() function, and listen for it on the <input /> tag. // near the top of the `form` component function handlechange(e) { console.log("typing!"); } // down in the return statement <input type="text" id="new-todo-input" classname="input...
...thing, and try your app again — now you can add tasks without getting that warning about duplicate ids. detour: counting tasks now that we can add new tasks, you may notice a problem: our heading reads 3 tasks remaining, no matter how many tasks we have! we can fix this by counting the length of tasklist and changing the text of our heading accordingly. add this inside your app() definition, before the return statement: const headingtext = `${tasklist.length} tasks remaining`; hrm. this is almost right, except that if our list ever contains a single task, the heading will still use the word “tasks”. we can make this a variable, too. update the code you just added as follows: const tasksnoun = tasklist.length !== 1 ? 'tasks' : 'task'; const headingtext = `${tasklist.length} ${tasksnou...
...And 2 more matches
The Firefox codebase: CSS Guidelines
en specify the styles in css. classlist is generally better than classname. there's less chance of overwriting an existing class. only use generic selectors such as :last-child, when it is what you mean semantically. if not, using a semantic class name is more descriptive and usually better. boilerplate make sure each file starts with the standard copyright header (see license boilerplate). before adding more css it is good practice to check if the css that is being written is needed, it can be the case that a common component has been already written could be reused with or without changes. most of the time, the common component already follows the a11y/theme standards defined in this guide. so, when possible, always prefer editing common components to writing your own. also, it is good...
...a common class when the new element you are styling reuses some styles from another element, this allows the maintenance cost and the amount of code duplication to be reduced. formatting spacing & indentation 2 spaces indentation is preferred add a space after each comma, except within color functions: linear-gradient(to bottom, black 1px, rgba(255,255,255,0.2) 1px) always add a space before !important. omit units on 0 values do this: margin: 0; not this: margin: 0px; use expanded syntax it is often harder to understand what the shorthand is doing and the shorthand can also hide some unwanted default values. it is good to privilege expanded syntax to make your intentions explicit. do this: border-color: red; not this: border: red; put multiple selectors on...
...true"]. avoid id selectors unless it is really the wanted goal, since ids have higher specificity and therefore are harder to override. using descendant selectors is good practice for performance when possible: for example: .autocomplete-item[selected] > .autocomplete-item-title would be more efficient than .autocomplete-item[selected] .autocomplete-item-title overriding css before overriding any css rules, check whether overriding is really needed. sometimes, when copy-pasting older code, it happens that the code in question contains unnecessary overrides. this could be because the css that it was overriding got removed in the meantime. in this case, simply dropping the override should work. it is also good practice to look at whether the rule you are overriding is still ...
...And 2 more matches
Performance best practices for Firefox front-end engineers
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 milliseconds or less, every frame. note that requestanimationframe() lets you queue up javascript to run right before the style flush occurs. this allows you to put all of your dom writes (most importantly, anything that could change the size or position of things in the dom) just before the style and layout steps of the pipeline, combining all the style and layout calculations into a single batch so it all happens once, in a single frame tick, instead of across multiple frames. see detecting and avoiding synchr...
...t the style information you’re asking for has something to do with size or position, you may also cause a layout recalculation (also referred to as layout flush or reflow), which is also an expensive step (see detecting and avoiding synchronous reflow below). to avoid this: avoid reading style information if you can. if you must read style information, do so at the very beginning of the frame, before any changes have been made to the dom since the last time a style flush occurred. historically, there hasn't been an easy way of doing this - however, bug 1434376 has recently landed some chromeonly helpers to the window binding to make this simpler. if you want to queue up some javascript to run after the next "natural" style and layout flush, try: // suppose we want to get the computed "disp...
... vaguest sense of what it is—and to only know to avoid it. this section will attempt to demystify things. the first time a document (xul or html) loads, we parse the markup, and then apply styles. once the styles have been calculated, we then need to calculate where things are going to be placed on the page. this layout step can be seen in the “16ms” pipeline graphic above, and occurs just before we paint things to be composited for the user to see. it is expected that over time, script will update the dom, requiring us to recalculate styles, and then update layout. normally, however, the changes to the dom just result in the standard style calculation that occurs immediately after the javascript has finished running during the 16ms window. interruptible reflow since the early days, ge...
...And 2 more matches
Download
lly downloaded data that can be used when restarting a failed or canceled download. this property is relevant while the download is in progress, and also if it failed or has been canceled. if the download has been completed successfully, this property is not relevant anymore. whether partial data can actually be retained depends on the saver and the download source, and may not be known before the download is started. hasprogress read only boolean indicates whether this download's progress property is able to report partial progress while the download proceeds, and whether the value in totalbytes is relevant. this depends on the saver and the download source. launchwhensucceeded boolean if this property is true when the download finishes successfully,...
...rties (for example, the succeeded property) instead. saver read only downloadsaver saver object associated with this download. source read only downloadsource source of this download. starttime read only date indicates the start time of the download. when the download starts, this property is set to a valid date object. the default value is null before the download starts. stopped read only boolean indicates that the download never started, has been completed successfully, failed, or has been canceled. this property becomes false when a download is started for the first time, or when a failed or canceled download is restarted. succeeded read only boolean this propery is true if the download has been completed suc...
...tarted for the first time, or when a failed or canceled download is restarted. succeeded read only boolean this propery is true if the download has been completed successfully. target read only downloadtarget target of this download. totalbytes read only number when hasprogress is true, this indicates the total number of bytes to be transferred before the download finishes; this value can be zero if the file is empty. note: this property's value may not match the actual final size of the downloaded file if the download is encoded during the network transfer. you can use the downloadtarget.size property to get the actual size of the completely-downloaded file once the download has succeeded. when hasprogress is false, this property is...
...And 2 more matches
Localizing with Koala
he magnifying glass icon on the right side of the bar. requirements mercurial, linux, windows or mac os x. instructions preparation install komodo edit. install koala extension. go to tools > add-ons. search for "koala". click add to komodo edit... restart komodo when the installation is complete. you should see a new button in komodo's toolbar, with two options: startpage and management. before you can use them, you need to create a new koala project. creating a new project create a new koala project by going to file > new > new project from template... choose "koala" in the categories list. choose "koala" in the templates list. choose a name for your project (e.g. l10n.kpf). choose the directory in which the project will live in (e.g. c:\mozilla\l10n on windows, /home/user/mozill...
...s used in the tooltip that appears when you hover over the magnifying glass icon in the search bar. once you translated the searchendcap.label entity, add the other one from this file, i.e. cmd_enginemanager.label. you can right-click it and choose "add entity" as you did previously, or just double-click the entity name to add it to the file. note how koala is smart enough to insert this entity before searchendcap.label. this is helpful for keeping the localization files clean and tidy at all times. the string to translated is selected so that you can translate it without any further clicking. when you are done with translating the cmd_enginemanager.label entity, save the file. now let's create the other file. double-click on search.properties and click "ok" when koala asks if you want to cre...
...just a simple key=value mapping. save the file to save your work. re-running the comparison a common scheme of working with the compare-locales tools (included in koala) is to incrementally translate and commit the files and then re-run comparison to see what is left to be translated. to make sure you're always translating the most recent en-us reference, you should update the source repository before you start working. open koala's start page. in "last used compares" click "update repo" to update the en-us repository to the most recent version. or, you can select firefox (3.6), en-us (included) and x-testing (3.6) in the "open" section below, and click "update repos" on the right. koala will re-run the comparison of your local localization files with the newest en-us reference and display t...
...And 2 more matches
Mozilla DOM Hacking Guide
y "correct behavior", i mean "the intended behavior with respect to the specification or de facto standard". we will see that class info is mainly used to implement the dom level 0. the w3c dom is mainly implemented in idl. the goals of class info are twofold: interface flattening, and implementing behaviors that are not possible with idl alone. a brief introduction to javascript and xpconnect. before we begin the explanation of class info, i'd like to introduce quickly the javascript engine and xpconnect. in javascript, there is no knowledge of types, like there is in c++. a function for example can be represented by a jsfunction, a jsobject, a jsval, ... this means that when we use the dom from javascript, we pass arguments that have no type. however, since the dom is coded in c++, we expect...
...sinfodata &data = sclassinfodata[aid]; data.mcachedclassinfo = data.u.mconstructorfptr(&data); ns_addref(data.mcachedclassinfo); } return sclassinfodata[aid].mcachedclassinfo; } here is the short explanation: this method returns the mcachedclassinfo member of the nsdomclassinfodata structure that corresponds to aid in the sclassinfodata array, if it exists, i.e. if this method has been called before. if it is called for the first time however, mcachedclassinfo is still a null pointer, and the function will create a new instance of the relevant helper class, and cache it in the mcachedclassinfo pointer, then return it. and for those interested, here the longer explanation. the first time getclassinfoinstance() is called, passing in an aid, mcachedclassinfo for that class will still be null.
...s. this is not for the faint of heart, and is not absolutely necessary, so you might want to skip this section if you don't have too much time (and i suppose you don't). user's guide to class info warning: this document has not yet been reviewed by the dom gurus, it might contain some errors. specifically, due to some changes that happened around, april 2002, some things that were not possible before are now possible. i will try to update this guide as soon as possible. please send any comment to fabian guisset. when should domclassinfo be used to add a new interface to an existing dom object to expose a new dom object to javascript to add a new js external constructor, like "new image()" to bypass the default behavior of xpconnect to implement a "replaceable" property to mess with ...
...And 2 more matches
How to embed the JavaScript engine
jsautorequest ar(cx); // in practice, you would want to exit this any // time you're spinning the event loop js::rootedobject global(cx, js_newglobalobject(cx, &global_class, nullptr)); if (!global) return 1; js::rootedvalue rval(cx); { // scope for jsautocompartment jsautocompartment ac(cx, glob...
... jsautorequest ar(cx); // in practice, you would want to exit this any // time you're spinning the event loop js::rootedobject global(cx, js_newglobalobject(cx, &global_class, nullptr, js::fireonnewglobalhook)); if (!global) return 1; js::rootedvalue rval(cx); { // scope for jsautocompartment jsau...
... jsautorequest ar(cx); // in practice, you would want to exit this any // time you're spinning the event loop js::rootedobject global(cx, js_newglobalobject(cx, &global_class, nullptr, js::fireonnewglobalhook)); if (!global) return 1; js::rootedvalue rval(cx); { // scope for jsautocompartment jsau...
...And 2 more matches
JSAPI User Guide
nullptr, nullptr, nullptr, nullptr, js_globalobjecttracehook }; // the error reporter callback. void reporterror(jscontext *cx, const char *message, jserrorreport *report) { fprintf(stderr, "%s:%u:%s\n", report->filename ? report->filename : "[no filename]", (unsigned int) report->lineno, message); } int run(jscontext *cx) { // enter a request before running anything in the context. jsautorequest ar(cx); // create the global object and a new compartment. rootedobject global(cx); global = js_newglobalobject(cx, &globalclass, nullptr, js::dontfireonnewglobalhook); if (!global) return 1; // enter the new global object's compartment. jsautocompartment ac(cx, global); // po...
...stack. several more examples of throwing and catching exceptions can be found in the jsapi phrasebook. error reports todo your custom errorreporter todo when errors are reported automatic handling of uncaught exceptions the js_compile*, js_call*, js_execute*, and js_evaluate* functions automatically pass exceptions to the error reporter in certain cases. each of these functions checks, just before it returns, to see if an exception is pending in the current jscontext. if so, it then checks to see if there is any other javascript script or function on the stack in that jscontext. if so, then the exception might yet be caught, so spidermonkey does nothing and returns false, allowing the exception to propagate. but if nothing is on the javascript stack, then the uncaught exception is passed t...
.../ my_static_props, my_static_methods); running scripts /* these should indicate source location for diagnostics. */ char *filename; unsigned int lineno; /* * the return value comes back here -- if it could be a gc thing, you must * add it to the gc's "root set" with js_add*root(cx, &thing) where thing * is a jsstring *, jsobject *, or jsdouble *, and remove the root before * rval goes out of scope, or when rval is no longer needed. */ jsval rval; jsbool ok; /* * some example source in a c string. larger, non-null-terminated buffers * can be used, if you pass the buffer length to js_evaluatescript. */ char *source = "x * f(y)"; ok = js_evaluatescript(cx, globalobj, source, strlen(source), filename, lineno, &rval); if (ok) { /* sho...
...And 2 more matches
SpiderMonkey 31
ted 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 31 the first change most embedders will notice is that spidermonkey must now be initialized before it can be used, using the newly-repurposed js_init method. after this method is called, normal jsapi operations are permitted. when all jsapi operation has completed, the corresponding js_shutdown method (currently non-mandatory, but highly recommended as it may become mandatory in the future) uninitializes spidermonkey, cleaning up memory and allocations performed by js_init. a major change t...
... flag. these and other changes are explained in detail below. new javascript language features javascript 31 includes significant updates to language features, yo. new c++ apis jsapi is now a c++-only api. please note that spidermonkey reserves the js:: namespace for itself (and the js:: namespace for internal use). js_init is a new function which must be used to initialize the js engine before any jsruntimes are created or other jsapi methods are called. this method pairs with the existing (currently non-mandatory) js_shutdown method, which uninitializes the js engine after all runtimes have been destroyed. js_seticumemoryfunctions is a new function which can be used to set the allocation and deallocation functions used by the icu internationalization library. this is unlikely to be...
...isting (currently non-mandatory) js_shutdown method, which uninitializes the js engine after all runtimes have been destroyed. js_seticumemoryfunctions is a new function which can be used to set the allocation and deallocation functions used by the icu internationalization library. this is unlikely to be of interest to embedders unless you are doing detailed memory profiling. it must be called before js_init is called. obsolete apis js_convertarguments "j" type deleted apis js_newgrowablestring (can be replaced with js_newucstring) js_isconstructing (can be replaced with callargs::isconstructing or callreceiver::isconstructing) js_valuetoboolean (replaced by js::toboolean) js_valuetonumber (can be replaced with js::tonumber) js_valuetoint64 (replaced by js::toint64) js_valuetou...
...And 2 more matches
Redis Tips
exity - each command's complexity is given in big-o notation. this is immensely helpful. related commands - an ever-growing list of related commands is given on the right-hand side of the page. recipes - at the bottom of many pages is a section that gives usage patterns or recipes for the command under discussion. there are many insightful ideas to be found here. getting started with redis before you go any further in this document, make sure you have played with redis for at least 5 or 10 minutes. if you have not, here is a fantastic on-line, interactive redis tutorial: http://try.redis.io/ for reference later on, you'll want the source of all things redis: https://redis.io you'll want to run a redis-server on your machine, and use the redis-cli at the command-line for hacking. n...
..., incrby, and incrbyfloat all increment counters. they are also atomic operations. they return the post-increment value of your key. redis> set foo 42 ok redis> incr foo (integer) 43 redis> incrby foo 17 (integer) 60 notice that these results come back as numbers, not strings. incrbyfloat is in redis 2.6. getset is awesome. it sets the value of a key, and returns the value the key had before you changed it. redis> del foo (integer) 1 redis> get foo (nil) redis> getset foo 3 (nil) redis> getset foo 4 "3" efficient multiple queries and transaction blocks you'll often want to do several queries together. each redis command results in one network round trip. so chaining lots of commands together is going to waste a lot of time. redis has a solution for this: transaction blocks...
...he others still all execute! (try this by breaking one of the set statements by leaving out the value argument.) you'll get one return value for each operation that didn't crash. this sounds terrifying, but it's not actually such a big deal in practice. commands will only crash if you feed them the wrong arguments or wrong number of arguments. and you'll probably find problems like that long before you go into production. optimistic locking your transactions are atomic once they start, but of course you can't guarantee that you'll get there first. the redis command watch lets you name keys you're worried about; it causes your next transaction to be immediately aborted if any of the watched keys has been modified by anyone else. for example, here's some node code: var redis = requi...
...And 2 more matches
Mozilla internal string guide
y() - the fastest way of determining if the string has any value. use this instead of testing string.length == 0 .equals(string) - true if the given string has the same value as the current string. common methods that modify the string: .assign(string) - assigns a new value to the string. .append(string) - appends a value to the string. .insert(string, position) - inserts the given string before the code unit at position. .truncate(length) - shortens the string to the given length. complete documentation can be found in the appendix. read-only strings the const attribute on a string determines if the string is writable. if a string is defined as a const nsastring then the data in the string cannot be manipulated. if one tries to call a non-const method on a const string the compiler...
...== *cur) { len -= 1; end -= 1; if (cur < end) memmove(cur, cur + 1, (end - cur) * sizeof(char16_t)); } else { cur += 1; } } data.setlength(len); } note that using beginwriting() to make a string longer is not ok. beginwriting() must not be used to write past the logical length of the string indicated by endwriting() or length(). calling setcapacity() before beginwriting() does not affect what the previous sentence says. to make the string longer, call setlength() before beginwriting() or use the bulkwrite() api described below. bulk write bulkwrite() allows capacity-aware cache-friendly low-level writes to the string's buffer. capacity-aware means that the caller is made aware of how the caller-requested buffer capacity was rounded up to mozjemal...
...sspan()) or via component accessors named consistently with those on span: elements() and length() the latter is not the logical length of the string but the writable length of the buffer. the buffer exposed via these methods includes the prefix that you may have requested to be preserved. it's up to you to skip past it so as to not overwrite it. if there's a need to request a different capacity before you are ready to call finish(), you can call restartbulkwrite() on the handle. it takes three arguments that match the first three arguments of bulkwrite(). it returns mozilla::result<mozilla::ok, nsresult> to indicate success or oom. calling restartbulkwrite() invalidates previously-obtained span, raw pointer or length. once you are done writing, call finish(). it takes two arguments: the new l...
...And 2 more matches
nsINavHistoryResultViewObserver
drop_on 0 the drag operation wishes to drop the dragged item onto the indicated row. drop_after 1 the drag operation wishes to insert the dragged item after the indicated row. methods candrop() implement this method to report whether or not a drop is permitted onto the speci...
...n column); void onselectionchanged(); void onperformaction(in wstring action); void onperformactiononrow(in wstring action, in long row); void onperformactiononcell(in wstring action, in long row, in nsitreecolumn column); constants constant value description drop_before -1 the drag operation wishes to insert the dragged item before the indicated row. drop_on 0 the drag operation wishes to drop the dragged item onto the indicated row. drop_after 1 the drag operation wishes to insert the dragged item after the indicated row. methods candrop() implement this method to report whether or not a drop is permitted onto the specified location. to provide behavior similar to the folder pane in thun...
...underbird, where drops are only permitted on items themselves instead of on the pane as a whole, always return false when the orientation isn't drop_on. warning: do not change the content of the observer list. boolean candrop( in long index, in long orientation ); parameters index the item over which the drag is currently located. ...
...And 2 more matches
nsITextInputProcessor
pecified with non-zero keycode attribute value, this causes throwing an excepction since it doesn't make sense. key_dont_dispatch_modifier_key_event 0x00000020 one of akeyflags. textinputprocessor manages modifier state with every modifier key events. in other words, when you need to specify modifier key state of dispatching keyboard events, you need to dispatch modifier key events before and after that. however, especially for keeping compatibility with legacy api, you may want to modify only the modifier state of a textinputprocessor instance. in this case, you can suppress textinputprocessor dispatches modifier key events with this flag. if this is specified for non-modifier key, it causes throwing an exception since it doesn't make sense. methods appendclausetopendingc...
...f alength must be same as the length of astring of setpendingcompositionstring(). void appendclausetopendingcomposition(in unsigned long alength, in unsigned long aattribute); parameters alength the length of appending clause. aattribute the attribute of appending clause. must be one of attr_* constants. begininputtransaction() this must be called before starting composition every time. this tries to get the rights to create composition on the window. if no other instance is composing on the window, this associates the instance with the window and registers the callback to the instance. boolean begininputtransaction(in nsidomwindow awindow, in nsitextinputprocessorcallback acallback); parameters awindow the do...
...in nsitextinputprocessorcallback acallback); parameters awindow the dom window which has focused editor. this must not be null. acallback the callback object. this must not be null. see the document of nsitextinputprocessorcallback for the details. return value returns true if the instance could create composition. otherwise, false. begininputtransactionfortests() this must be called before starting composition for automated tests every time. this tries to get the rights to create composition on the window. if no other instance is composing on the window, this associates the instance with the window and registers the callback to the instance if it's specified. boolean begininputtransactionfortests(in nsidomwindow awindow, in nsitextinputprocess...
...And 2 more matches
Basic operations - Firefox Developer Tools
to enable it, open the developer tool settings, and check the "memory" box under "default firefox developer tools": from firefox 50 onwards, the memory tool is enabled by default. taking a heap snapshot to take a snapshot of the heap, click the "take snapshot" button, or the camera icon on the left: the snapshot will occupy the large pane on the right-hand side. on the left, you'll see an entry for the new snapshot, including its timestamp, size, and controls to save or clear this snapshot: clearing a snapshot to remove a snapshot, click the "x" icon: saving and loading snapshots if you close the memory tool, all unsaved snapshots will be discarded. ...
...lick the "x" icon: saving and loading snapshots if you close the memory tool, all unsaved snapshots will be discarded. to save a snapshot click "save": you'll be prompted for a name and location, and the file will be saved with an .fxsnapshot extension. ...
...the tool then shows you the differences between the two snapshots: when you're looking at a comparison, you can't use the dominators view or the tree map view. ...
...And 2 more matches
BiquadFilterNode() - Web APIs
s://github.com/mdn/browser-compat-data and send us a pull request. ...
...s before chrome 59, the default values were not supported.edge full support ≤79firefox full support 53ie no support noopera full support 42notes full support 42notes notes before opera 46, the default values were not supported.safari ? ...
... noopera full support 42notes full support 42notes notes before opera 46, the default values were not supported.safari ? ...
...And 2 more matches
Using images - Web APIs
if the hosting domain permits cross-domain access to the image, the image can be used in your canvas without tainting it; otherwise using the image will taint the canvas. using other canvas elements just as with normal images, we access other canvas elements using either the document.getelementsbytagname() or document.getelementbyid() method. be sure you've drawn something to the source canvas before using it in your target canvas. one of the more practical uses of this would be to use a second canvas element as a thumbnail view of the other larger canvas. creating an image from scratch another option is to create new htmlimageelement objects in our script. to do this, you can use the convenient image() constructor: var img = new image(); // create new img element img.src = 'myimage.png...
...s a thumbnail view of the other larger canvas. creating an image from scratch another option is to create new htmlimageelement objects in our script. to do this, you can use the convenient image() constructor: var img = new image(); // create new img element img.src = 'myimage.png'; // set source path when this script gets executed, the image starts loading. ...
...onvenient image() constructor: var img = new image(); // create new img element img.src = 'myimage.png'; // set source path when this script gets executed, the image starts loading. if you try to call drawimage() before the image has finished loading, it won't do anything (or, in older browsers, may even throw an exception). so you need to be sure to use the load event so you don't try this before the image has loaded: var img = new image(); // create new img element img.addeventlistener('load', function() { // execute drawimage statements here }, false); img.src = 'myimage.png'; // set source path if you're only using one external image this can be a good approach, but once you need to track more than one we need to resort to something more clever. it's beyond the scope of this tut...
...And 2 more matches
EffectTiming.fill - Web APIs
Web › API › EffectTiming › fill
the web animations api's effecttiming dictionary's fill property specifies a fill mode, which defines how the element to which the animation is applied should look when the animation sequence is not actively running, such as before the time specified by iterationstart or after animation's end time. for example, setting fill to "none" means the animation's effects are not applied to the element if the current time is outside the range of times during which the animation is running, while "forwards" ensures that once the animation's end time has been passed, the element will continue to be drawn in the state it was in at its last rendered frame. note that authors are discouraged from using fill modes to persist the effect of an animation indefinitely. see the alternatives to fill mode...
...rm: "rotate(90deg)" } ]; the boxrotationkeyframes object is an array of keyframes, each describing the state of the affected element at a point in the animation process. in this case, we have just two keyframes; the first defines what affect is applied to the element immediately after the animation first begins to play, and the second defines the effect applied to the element in the last moment before it ends. those phrases are crucial. let's look at why. the first keyframe says that when the animation begins, the element should be rotated 90° to the left. that means that unless we specify otherwise using the fill property, the instant the animation is started the element will be rotated to the left 90°, and then it will animate smoothly from there. since by default the box isn't rotated, ...
...default the box isn't rotated, the last keyframe says that the animation's final frame should draw the animation rotated 90° to the right from its original orientation. var boxrotationtiming = { duration: 2000, iterations: 1, fill: "none" }; the boxrotationtiming object describes how long the animation should take to run, how many times it should run, what state the element should be in before the animation begins and after it ends, and so forth. here we specify that the animation should take 2000 milliseconds (2 seconds) to complete, should only run once, and that the fill mode should be "none". as defined above, the "none" fill mode means that the element will be rendered in its natural, unaltered condition anytime the animation isn't actively running. document.getelementbyid("anim...
...And 2 more matches
Event - Web APIs
Web › API › Event
and the processing order of such events depends on the event bubbling and capture settings of each handler triggered. interfaces based on event below is a list of interfaces which are based on the main event interface, with links to their respective documentation in the mdn api reference. note that all event interfaces have names which end in "event". ...
...g order of such events depends on the event bubbling and capture settings of each handler triggered. interfaces based on event below is a list of interfaces which are based on the main event interface, with links to their respective documentation in the mdn api reference. note that all event interfaces have names which end in "event". ...
...e documentation in the mdn api reference. note that all event interfaces have names which end in "event". ...
...And 2 more matches
HTMLTableElement - Web APIs
ption> that is a child of this element is removed from the tree, if any. htmltableelement.thead is a htmltablesectionelement representing the first <thead> that is a child of the element, or null if none is found. when set, if the object doesn't represent a <thead>, a domexception with the hierarchyrequesterror name is thrown. if a correct object is given, it is inserted in the tree immediately before the first element that is neither a <caption>, nor a <colgroup>, or as the last child if there is no such element, and the first <thead> that is a child of this element is removed from the tree, if any. htmltableelement.tfoot is a htmltablesectionelement representing the first <tfoot> that is a child of the element, or null if none is found. when set, if the object doesn't represent a <tfoot>, ...
...thead> that is a child of this element is removed from the tree, if any. htmltableelement.tfoot is a htmltablesectionelement representing the first <tfoot> that is a child of the element, or null if none is found. when set, if the object doesn't represent a <tfoot>, a domexception with the hierarchyrequesterror name is thrown. if a correct object is given, it is inserted in the tree immediately before the first element that is neither a <caption>, a <colgroup>, nor a <thead>, or as the last child if there is no such element, and the first <tfoot> that is a child of this element is removed from the tree, if any. htmltableelement.rowsread only returns a live htmlcollection containing all the rows of the element, that is all <tr> that are a child of the element, or a child of one of its <thead...
... domstring containing the length in pixels or in percentage of the desired width fo the entire table. it reflects the obsolete width attribute. methods inherits methods from its parent, htmlelement. htmltableelement.createthead() returns an htmlelement representing the first <thead> that is a child of the element. if none is found, a new one is created and inserted in the tree immediately before the first element that is neither a <caption>, nor a <colgroup>, or as the last child if there is no such element. htmltableelement.deletethead() removes the first <thead> that is a child of the element. htmltableelement.createtfoot() returns an htmlelement representing the first <tfoot> that is a child of the element. if none is found, a new one is created and inserted in the tree immediatel...
...And 2 more matches
PerformanceNavigationTiming - Web APIs
following performanceresourcetiming properties for navigation performance entry types by qualifying and constraining them as follows: performanceresourcetiming.initiatortyperead only returns "navigation". the interface also supports the following properties: performancenavigationtiming.domcomplete read only a domhighrestimestamp representing a time value equal to the time immediately before the browser sets the current document readiness of the current document to complete. performancenavigationtiming.domcontentloadedeventend read only a domhighrestimestamp representing the time value equal to the time immediately after the current document's domcontentloaded event completes. performancenavigationtiming.domcontentloadedeventstart read only a domhighrestimestamp representing th...
...iness of the current document to complete. performancenavigationtiming.domcontentloadedeventend read only a domhighrestimestamp representing the time value equal to the time immediately after the current document's domcontentloaded event completes. performancenavigationtiming.domcontentloadedeventstart read only a domhighrestimestamp representing the time value equal to the time immediately before the user agent fires the domcontentloaded event at the current document. performancenavigationtiming.dominteractive read only a domhighrestimestamp representing a timestamp representing the time value equal to the time immediately before the user agent sets the current document readiness of the current document to interactive. performancenavigationtiming.loadeventend read only a domhighrest...
... performancenavigationtiming.redirectcount read only a number representing the number of redirects since the last non-redirect navigation under the current browsing context. ...
...And 2 more matches
SVGSVGElement - Web APIs
h the given ui event occurred. when the browser actually knows the physical size of a "screen unit", this float attribute will express that information; otherwise, user agents will provide a suitable default value (such as .28mm). svgsvgelement.screenpixeltomillimetery corresponding size of a screen pixel along the y-axis of the viewport. svgsvgelement.usecurrentview the initial view (i.e., before magnification and panning) of the current innermost svg document fragment can be either the "standard" view, i.e., based on attributes on the <svg> element such as viewbox) or on a "custom" view (i.e., a hyperlink into a particular <view> or other element). if the initial view is the "standard" view, then this attribute is false. if the initial view is a "custom" view, then this attribute is true...
... be either the "standard" view, i.e., based on attributes on the <svg> element such as viewbox) or on a "custom" view (i.e., a hyperlink into a particular <view> or other element). if the initial view is the "standard" view, then this attribute is false. if the initial view is a "custom" view, then this attribute is true. svgsvgelement.currentview an svgviewspec defining the initial view (i.e., before magnification and panning) of the current innermost svg document fragment. the meaning depends on the situation: if the initial view was a "standard" view, then: the values for viewbox, preserveaspectratio and zoomandpan within currentview will match the values for the corresponding dom attributes that are on svgsvgelement directly the values for transform and viewtarget within currentview ...
...ns that are defined within the svg document fragment, causing the animation clock to continue from the time at which it was suspended. svgsvgelement.animationspaused() returns true if this svg document fragment is in a paused state. svgsvgelement.getcurrenttime() returns the current time in seconds relative to the start time for the current svg document fragment. ...
...And 2 more matches
Using Service Workers - Web APIs
finally fix these issues. service worker syntax is more complex than that of appcache, but the trade off is that you can use javascript to control your appcache-implied behaviors with a fine degree of granularity, allowing you to handle this problem and many more. using a service worker you can easily set an app up to use cached assets first, thus providing a default experience even when offline, before then getting more data from the network (commonly known as offline first). this is already available with native apps, which is one of the main reasons native apps are often chosen over web apps. setting up to play with service workers many service workers features are now enabled by default in newer versions of supporting browsers. if however you find that demo code is not working in your inst...
... callback. let’s compare a traditional synchronous callback structure to its asynchronous promise equivalent. ...
...t for myfunction() to run and return value before any more of the code can execute. in the second example, myfunction() returns a promise for value, then the rest of the code can carry on running. when the promise resolves, the code inside then will be run, asynchronously. now for a real example — what if we wanted to load images dynamically, but we wanted to make sure the images were loaded before we tried to display them? this is a standard thing to want to do, but it can be a bit of a pain. we can use .onload to only display the image after it’s loaded, but what about events that start happening before we start listening to them? we could try to work around this using .complete, but it’s still not foolproof, and what about multiple images? and, ummm, it’s still synchronous, so bloc...
...And 2 more matches
Starting up and shutting down a WebXR session - Web APIs
you will learn how to do these things in this article. ...
... tools panel that lets you control the position and orientation of the headset and any hand controllers, as well as button presses on the controllers. emulator usage while somewhat awkward compared to using an actual headset, this makes it possible to experiment with and developer webxr code on a desktop computer, where webxr isn't normally available. ...
...h and developer webxr code on a desktop computer, where webxr isn't normally available. it also lets you perform some basic testing before taking your code to a real device. be aware, however, that the emulator does not yet completely emulate all of the webxr api, so you may run into problems you're not expecting. again, carefully read the readme file and make sure you're aware of the limitations before you begin. important: you should always test your code on actual ar and/or vr hardware before releasing or shipping a product! emulated, simulated, or polyfilled environments are not an adequate substitute for actual testing on physical devices. getting the extension download the webxr api emulator for your supported browser below: google chrome mozilla firefox the source code for the ex...
...And 2 more matches
Using XMLHttpRequest - Web APIs
ontaining 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 parsing and serializing xml to strings or objects. using xmlserializer to serialize dom trees to strings or to files. regexp can be used if you always know the content of the xml document beforehand. you might want to remove line breaks, if you use regexp to scan with regard to line breaks. however, this method is a "last resort" since if the xml code changes slightly, the method will likely fail. note: xmlhttprequest can now interpret html for you using the responsexml property. read the article about html in xmlhttprequest to learn how to do this. processing a responsetext propert...
...cult to manipulate and analyze. there are three primary ways to analyze and parse this raw html string: use the xmlhttprequest.responsexml property as covered in the article html in xmlhttprequest. inject the content into the body of a document fragment via fragment.body.innerhtml and traverse the dom of the fragment. regexp can be used if you always know the content of the html responsetext beforehand. you might want to remove line breaks, if you use regexp to scan with regard to linebreaks. however, this method is a "last resort" since if the html code changes slightly, the method will likely fail. handling binary data although xmlhttprequest is most commonly used to send and receive textual data, it can be used to send and receive binary content. there are several well tested methods ...
....log("the transfer is complete."); } function transferfailed(evt) { console.log("an error occurred while transferring the file."); } function transfercanceled(evt) { console.log("the transfer has been canceled by the user."); } lines 3-6 add event listeners for the various events that are sent while performing a data transfer using xmlhttprequest. note: you need to add the event listeners before calling open() on the request. otherwise the progress events will not fire. the progress event handler, specified by the updateprogress() function in this example, receives the total number of bytes to transfer as well as the number of bytes transferred so far in the event's total and loaded fields. however, if the lengthcomputable field is false, the total length is not known and will be zero. ...
...And 2 more matches
Color picker tool - CSS: Cascading Style Sheets
inear-gradient(top, hsl(0, 0%, 100%) 0%, hsla(0, 0%, 100%, 0) 50%, hsla(0, 0%, 0%, 0) 50%, hsl(0, 0%, 0%) 100%), -o-linear-gradient(left, hsl(0, 0%, 50%) 0%, hsla(0, 0%, 50%, 0) 100%); background-color: #f00; } .ui-color-picker .picker { width: 10px; height: 10px; border-radius: 50%; border: 1px solid #fff; position: absolute; top: 45%; left: 45%; } .ui-color-picker .picker:before { width: 8px; height: 8px; content: ""; position: absolute; border: 1px solid #999; border-radius: 50%; } .ui-color-picker .hue, .ui-color-picker .alpha { width: 198px; height: 28px; margin: 5px; border: 1px solid #fff; float: left; } .ui-color-picker .hue { background: url("https://mdn.mozillademos.org/files/5701/hue.png") center; background: -moz-linear-gradient(left, #f00 0%, #f...
... height: 24px; padding: 2px 0; -moz-box-sizing: border-box; -webkit-box-sizing: border-box; box-sizing: border-box; } /* preview color */ .ui-color-picker .preview { width: 95px; height: 53px; margin: 5px; margin-top: 10px; border: 1px solid #ddd; background-image: url("https://mdn.mozillademos.org/files/5705/alpha.png"); float: left; position: relative; } .ui-color-picker .preview:before { height: 100%; width: 50%; left: 50%; top: 0; content: ""; background: #fff; position: absolute; z-index: 1; } .ui-color-picker .preview-color { width: 100%; height: 100%; background-color: rgba(255, 0, 0, 0.5); position: absolute; z-index: 1; } .ui-color-picker .switch_mode { width: 10px; height: 20px; position: relative; border-radius: 5px 0 0 5px; border: 1px solid #ddd; ...
...: url('https://mdn.mozillademos.org/files/6065/arrow.png') center no-repeat; width: 100%; height: 12px; top: -12px; z-index: 2; } #picker-samples #add-icon { width: 100%; height: 100%; position: relative; box-shadow: inset 0px 0px 2px 0px #ddd; } #picker-samples #add-icon:hover { cursor: pointer; border-color: #ddd; box-shadow: inset 0px 0px 5px 0px #ccc; } #picker-samples #add-icon:before, #picker-samples #add-icon:after { content: ""; position: absolute; background-color: #eee; box-shadow: 0 0 1px 0 #eee; } #picker-samples #add-icon:before { width: 70%; height: 16%; top: 42%; left: 15%; } #picker-samples #add-icon:after { width: 16%; height: 70%; top: 15%; left: 42%; } #picker-samples #add-icon:hover:before, #picker-samples #add-icon:hover:after { background-color...
...And 2 more matches
Printing - Developer guides
ontent. there are a number of possible scenarios: you wish to adjust layout to take advantage of the size and shape of the paper. you wish to use different styles to enhance the appearance of your content on paper. you wish to use higher resolution images for a better result. you want to adjust the user experience of printing, such as presenting a specially-formatted version of your content before printing begins. there may be other cases in which you want to manage the printing process, but these are some of the most common scenarios. this article provides tips and techniques for helping your web content print better. using a print style sheet add the following to your <head> tag. <link href="/path/to/print.css" media="print" rel="stylesheet" /> using media queries to improve layou...
...se are some of the most common scenarios. this article provides tips and techniques for helping your web content print better. using a print style sheet add the following to your <head> tag. ...
... examples here are some common examples. ...
...And 2 more matches
Control flow and error handling - JavaScript
sions. block statement the most basic statement is a block statement, which is used to group statements. the block is delimited by a pair of curly brackets: { statement_1; statement_2; ⋮ statement_n; } example block statements are commonly used with control flow statements (if, for, while). while (x < 10) { x++; } here, { x++; } is the block statement. important: javascript before ecmascript2015 (6th edition) does not have block scope! in older javascript, variables introduced within a block are scoped to the containing function or script, and the effects of setting them persist beyond the block itself. in other words, block statements do not define a scope. "standalone" blocks in javascript can produce completely different results from what they would produce in c or ja...
...f setting them persist beyond the block itself. in other words, block statements do not define a scope. "standalone" blocks in javascript can produce completely different results from what they would produce in c or java. for example: var x = 1; { var x = 2; } console.log(x); // outputs 2 this outputs 2 because the var x statement within the block is in the same scope as the var x statement before the block. (in c or java, the equivalent code would have outputted 1.) since ecmascript2015, the let and const variable declarations are block-scoped. see the let and const reference pages for more information. conditional statements a conditional statement is a set of commands that executes if a specified condition is true. javascript supports two conditional statements: if...else and switch...
...ou want the try block to succeed—but if it does not, you want control to pass to the catch block. if any statement within the try block (or in a function called from within the try block) throws an exception, control immediately shifts to the catch block. if no exception is thrown in the try block, the catch block is skipped. the finally block executes after the try and catch blocks execute but before the statements following the try...catch statement. the following example uses a try...catch statement. the example calls a function that retrieves a month name from an array based on the value passed to the function. if the value does not correspond to a month number (1–12), an exception is thrown with the value "invalidmonthno" and the statements in the catch block set the monthname variable...
...And 2 more matches
Using Promises - JavaScript
essentially, a promise is a returned object to which you attach callbacks, instead of passing callbacks into a function. ...
...n(successcallback, failurecallback); that's shorthand for: const promise = createaudiofileasync(audiosettings); promise.then(successcallback, failurecallback); we call this an asynchronous function call. this convention has several advantages. we will explore each one. guarantees unlike old-fashioned passed-in callbacks, a promise comes with some guarantees: callbacks will never be called before the completion of the current run of the javascript event loop. callbacks added with then(), as above, will be called even after the success or failure of the asynchronous operation. multiple callbacks may be added by calling then() several times. each callback is executed one after another, in the order in which they were inserted. one of the great things about using promises is chaining. c...
...atch, which is useful to accomplish new actions even after an action failed in the chain. read the following example: new promise((resolve, reject) => { console.log('initial'); resolve(); }) .then(() => { throw new error('something failed'); console.log('do this'); }) .catch(() => { console.error('do that'); }) .then(() => { console.log('do this, no matter what happened before'); }); this will output the following text: initial do that do this, no matter what happened before note: the text do this is not displayed because the something failed error caused a rejection. error propagation you might recall seeing failurecallback three times in the pyramid of doom earlier, compared to only once at the end of the promise chain: dosomething() .then(result => dosomethi...
...And 2 more matches
Web video codec guide - Web media technologies
e this, and to improve seek time through the video data, periodic key frames (also known as intra-frames or i-frames) are placed into the video file. the key frames are full frames, which are used to repair any damage or artifact residue that's currently visible. aliasing aliasing is a general term for anything that upon being reconstructed from the encoded data does not look the same as it did before compression. there are many forms of aliasing; the most common ones you may see include: moiré patterns a unknown prefix: moiré pattern. is a large-scale spatial interference pattern produced when a pattern in the source image and the manner in which the encoder operates are slightly out of alignment spatially. the artifacts generated by the encoder then introduce strange, s...
... there are forms of motion compensation that allow for variable block sizes, and even for blocks to overlap. there are, however, artifacts that can occur due to motion compensation. these occur along block borders, in the form of sharp edges that produce false ringing and other edge effects. these are due to the mathematics involved in the coding of the residual frames, and can be easily noticed before being repaired by the next key frame. reduced frame size in certain situations, it may be useful to reduce the video's dimensions in order to improve the final size of the video file. while the immediate loss of size or smoothness of playback may be a negative factor, careful decision-making can result in a good end result. if a 1080p video is reduced to 720p prior to encoding, the resulting vi...
...to accomplish even more for you. for exmaple, instead of computing motion differences for two frames that are two pixels apart due to inter-frame motion, skipping every other frame could lead to computing a difference that comes out to four pixels of movement. this lets the overall movement of the camera be represented by fewer residual frames. the absolute minimum frame rate that a video can be before its contents are no longer perceived as motion by the human eye is about 12 frames per second. less than that, and the video becomes a series of still images. motion picture film is typically 24 frames per second, while standard definition television is about 30 frames per second (slightly less, but close enough) and high definition television is between 24 and 60 frames per second. anything from...
...And 2 more matches
Mapping the width and height attributes of media container elements to their aspect-ratio - Web media technologies
read on to find out more. ...
...; } 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 make space for it. a new way of sizing images before loading completes recognizing the problem, a wicg community group formed to propose an intrinsicsize attribute. folks from mozilla then expanded on this thinking, working on a proposal in the css box sizing level 4 draft to define an aspect-ratio property and propose the idea of using the width and height attributes to compute layout. fantasai & jen simmons collaborated with emilio, who worked o...
...e width and height attributes to compute layout. fantasai & jen simmons collaborated with emilio, who worked on an experimental implementation to prove it would work. mozilla then brought the idea up in the wicg community group and discussed it further until representatives from chrome were onboard with the idea. due to this work, browsers are working on adding a new mechanism for sizing images before the actual image is loaded. firefox has added an internal aspect-ratio property (in version 69 onwards) that applies to replaced elements, and other related elements that accept width and height attributes. this appears in the browser's internal ua stylesheet, similar to the following: img, input[type="image"], video, embed, iframe, marquee, object, table { aspect-ratio: attr(width) / attr(hei...
...And 2 more matches
Communicating With Other Scripts - Archive of obsolete content
see content scripts: communicating with the add-on: content script to content script. page scripts if a page includes its own scripts using <script> tags, either embedded in the page or linked to it using the src attribute, there are a couple of ways a content script can communicate with it: using the dom postmessage() api using custom dom events using the dom postmessage api note that before firefox 31 code in content scripts can't use window to access postmessage() and addeventlistener() and instead must use document.defaultview. see the section below on using postmessage() before firefox 31. you can communicate between the content script and page scripts using window.postmessage(). messaging from content script to page script suppose we have a page called "listen.html" hosted a...
...so the content scripts in the above examples need to be rewritten like this: // content-script.js document.defaultview.postmessage("message from content script", "...
...so the content scripts in the above examples need to be rewritten like this: // content-script.js document.defaultview.postmessage("message from content script", "http://my-domain.org/"); // content-script.js document.defaultview.a...
...using postmessage() you can use custom dom events to communicate between page scripts and content scripts. messaging from content script to page script from firefox 30 onwards, the execution environment for content scripts has changed, so content scripts can't directly share objects with page scripts. this affects the use of custom events to send messages from content scripts to page scripts. before firefox 30 here's an example showing how to use custom dom events to send a message from a content script to a page script, before firefox 30. first, "main.js" will create a page-mod that will attach "content-script.js" to the target web page, and will then load the target web page: var tabs = require("sdk/tabs"); var mod = require("sdk/page-mod"); var self = require("sdk/self"); var pageurl...
Interacting with page scripts - Archive of obsolete content
issions” key in package.json, and set it to true. "permissions": { "unsafe-content-script": true } this is only a temporary migration aid, and will be removed eventually. communicating with page scripts there are two different ways a content script can communicate with a page script: using the dom postmessage() api using custom dom events using the dom postmessage api note that before firefox 31 code in content scripts can't use window to access postmessage() and addeventlistener() and instead must use document.defaultview. see the section below on using postmessage() before firefox 31. you can communicate between the content script and page scripts using window.postmessage(). content script to page script suppose we have a page called "listen.html" hosted at "my-domain.or...
...so the content scripts in the above examples need to be rewritten like this: // talk.js document.defaultview.postmessage("message from content script", "http://my-...
...so the content scripts in the above examples need to be rewritten like this: // talk.js document.defaultview.postmessage("message from content script", "http://my-domain.org/"); // listen.js document.defaultview.addeventlistener('m...
...alternative to using postmessage() you can use custom dom events to communicate between page scripts and content scripts. content script to page script from firefox 30 onwards, the execution environment for content scripts has changed, so content scripts can't directly share objects with page scripts. this affects the use of custom events to send messages from content scripts to page scripts. before firefox 30 here's an example showing how to use custom dom events to send a message from a content script to a page script, before firefox 30. first, "main.js" will create a page-mod that will attach "content-script.js" to the target web page, and will then load the target web page: var tabs = require("sdk/tabs"); var mod = require("sdk/page-mod"); var self = require("sdk/self"); var pageurl...
widget - Archive of obsolete content
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 property are loaded before those 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. this may take one of the f...
...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. this may take one of the following values: "start": load content scripts immediately after the document element for the widget is inserted into the dom, but before the dom content itself has been loaded "ready": load content scripts once dom content has been loaded, corresponding to the domcontentloaded event "end": load content scripts once all the content (dom, js, css, images) for the widget has been loaded, at the time the window.onload event fires this property is optional and defaults to "end". contentscriptoptions ...
...tscriptfile a local file url or an array of local file urls of content scripts to load. contentscript a string or an array of strings containing the texts of content scripts to load. contentscriptwhen when to load the content scripts. this may have one of the following values: "start": load content scripts immediately after the document element for the widget is inserted into the dom, but before the dom content itself has been loaded "ready": load content scripts once dom content has been loaded, corresponding to the domcontentloaded event "end": load content scripts once all the content (dom, js, css, images) for the widget has been loaded, at the time the window.onload event fires contentscriptoptions read-only value exposed to content scripts under self.options property. any kin...
...ptfile a local file url or an array of local file urls of content scripts to load. contentscript a string or an array of strings containing the texts of content scripts to load. contentscriptwhen when to load the content scripts. this may have one of the following values: "start": load content scripts immediately after the document element for the widget view is inserted into the dom, but before the dom content itself has been loaded "ready": load content scripts once dom content has been loaded, corresponding to the domcontentloaded event "end": load content scripts once all the content (dom, js, css, images) for the widget view has been loaded, at the time the window.onload event fires contentscriptoptions read-only value exposed to content scripts under self.options property. an...
lang/functional - Archive of obsolete content
imeout(function () { ... }, 0)), except that the wrapped function may be reused and does not need to be repeated each time. this also enables you to use these functions as event listeners. let { defer } = require("sdk/lang/functional"); let fn = defer(function myevent (event, value) { console.log(event + " : " + value); }); fn("click", "#home"); console.log("done"); // this will print 'done' before 'click : #home' since // we deferred the execution of the wrapped `myevent` // function, making it non-blocking and executing on the // next event loop parameters fn : function the function to be deferred. returns function : the new, deferred function. remit() an alias for defer. invoke(callee, params, self) invokes callee, passing params as an argument and self as this. returns the valu...
...!"; function greet (name) { return "hi: " + name; } function exclaim (statement) { return statement + "!"; } parameters fn... : function takes a variable number of functions as arguments and composes them from right to left. returns function : the composed function. wrap(fn, wrapper) returns the first function passed as an argument to the second, allowing you to adjust arguments, run code before and after, and conditionally execute the original function. let { wrap } = require("sdk/lang/functional"); let wrappedhello = wrap(hello, function (fn, name) { return "before, " + fn(name) + "after"; }); wrappedhello("moe"); // "before, hello: moe, after" function hello (name) { return "hello: " + name; } parameters fn : function the function to be passed into the wrapper function. wrap...
...on of the function which, when invoked, will not be executed until it has not been invoked for wait milliseconds. this means that if the function's called many times in quick succession the function will only execute once, after the blizzard of calls has finished. this could be useful, for example, if we are checking the user's keyboard input, and want to wait until they've paused in their typing before we do so. parameters fn : function the function to debounce. wait : integer the number of milliseconds to wait before the function is executed. returns function : the debounced version of fn. throttle(fn, wait, options) this function is new in firefox 30. from underscore's throttle() function: this takes a function and returns a new version of the function which, when invoked repeated...
...bounced version of fn. throttle(fn, wait, options) this function is new in firefox 30. from underscore's throttle() function: this takes a function and returns a new version of the function which, when invoked repeatedly, will not excute the function more than once per wait milliseconds. parameters fn : function the function to debounce. wait : integer the number of milliseconds to wait before the function is executed. options : object by default the function is called as soon as it is invoked (the leading edge of the wait period), and at the end of wait (the trailing edge of the wait period). pass {leading : false} to stop the function being called at the leading edge, and {trailing : false} to stop it being called at the trailing edge. returns function : the throttled version of ...
Creating custom Firefox extensions with the Mozilla build system - Archive of obsolete content
in your extension include: need for high-performance beyond what can be delivered by javascript code. use of third-party libraries written in c or c++. use of mozilla interfaces that are not exposed via xpcom (e.g. nspr). note: with the modern jit javascript engine in gecko and js-ctypes more extension code can be written only in javascript than ever before. please consider all of your options carefully before deciding to use native code (c++) in your extension. in addition, binary components need to be recompiled for every major firefox release, which can be frustrating. this article describes how to set up the development environment for a large, complex firefox extension with any or all of the above-mentioned requirements. i should also s...
...y 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 to the templates, but the extra flexibility gained from having the makefiles generated dynamically is one of the things that makes the build system so powerf...
...s. (if something goes wrong, figure out what, fix it and then come back here and add it to this article.) to make sure that the build really finished, launch firefox and check that your extension is listed when you select tools/extensions. if you are using firefox as your regular browser (and if you're not, why not!?), you might be annoyed by the fact that you have to close regular firefox before running your custom-built version. if so, try setting the moz_no_remote environment variable to "1" before running the development version of firefox. you'll also need to use a different profile for your development version: firefox -p development where development is replaced with the name of the extra profile you've created. this will let you run both versions of firefox simultane...
...e. in this case, i would recommend placing the entire library distribution inside the project or subproject that uses it. so if library acmelib is used inside the multifarious/ subproject in the above example, it would be placed as a subdirectory underneath that subproject (at the same level as public/ and src/). of course, this means that you will have to build acmelib manually on all platforms before launching the mozilla build. but at least you can then refer to include files and import libraries from your component using relative paths. building for multiple platforms todo original document information author: matthew gertner - july 26, 2005. permission granted to migrate in jan 2006, including permission to relicense under the cc:by-sa. original source: http://www.allpeers.com/blo...
Enhanced Extension Installation - Archive of obsolete content
atibility is checked for by the new _getinstalldata function. this function returns the guid, version, and type of the item, and also an error code listing either success, or the reason for a failure, such as invalid guid, version, or incompatible item. depending on the failure, the install function may take several steps. if the item is found incompatible, a version update check is performed as before. if updated compatibility information is found this is written into the in-memory representation of the the temporary install manifest and the install function is called recursively, supplying this updated install manifest as the source for _getinstalldata. if the item is determined compatible by either of the above processes, a copy of the item's file is staged into the install location directo...
...add it to the extension container and set the same set of initial setup properties on it that we used to, with the addition of the installlocation key and the type value. at this stage we rewrite the extensions-startup.manifest and extensions.ini manifests and create the .autoreg file in the profile directory. ...
...n of the installlocation key and the type value. at this stage we rewrite the extensions-startup.manifest and extensions.ini manifests and create the .autoreg file in the profile directory. finalization on the next startup, the startup system discovers the .autoreg file (as before) and starts the extension system with the dirty flag, which causes the system to scan for items to be installed as before. ...
...rectory. finalization on the next startup, the startup system discovers the .autoreg file (as before) and starts the extension system with the dirty flag, which causes the system to scan for items to be installed as before. regardless of whether or not the extension system is called from the startup process with the dirty flag set to true (i.e. the startup process discovered the .autoreg file, before pending operations are finalized the extension system reads the extensions-startup.manifest and scans all of the install locations looking for items that match the following criteria: item in install location is not listed in startup manifest (new item being installed by just appearing in the install location). item in install location is listed in startup manifest, but its mtime is different...
Chapter 3: Introduction to XUL—How to build a more intuitive UI - Archive of obsolete content
note: if you want to contribute to this document please follow the guidelines on the contribute page. « 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. there are earlier experiments going back a long way in developing user interfaces using a combination of html and scripting languages, and xul could b...
... <button label="mixed4"/> </hbox> listing 3: horizontal and vertical boxes figure 1: output of listing 3 there is also a grid element, which can be used for layouts similar to those achieved using the html table element, a stack element for layering other elements, and so on. all on-screen widgets are laid out using these boxes, making complex interface designs possible. common attributes before we look at the various interface objects, let's look at some of their common attributes, especially the frequently used ones. id and class the attributes id and class fill the same role that the xhtml attributes of the same names fill. id is used to define a unique name for an element, and class is used to classify elements; both of these provide convenient ways to refer to elements in css and ...
...attributes and values merged with the overlay document. try overwriting the contents of overlaydocument.xul with listing 25 and re-saving. <?xml version="1.0" encoding="utf-8"?> <overlay xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> <hbox id="box1" align="center" style="border: 1px solid; margin: 1em;"> <button label="button 1"/> <button label="button 2" insertbefore="label1"/> </hbox> <button label="button 3"/> </overlay> listing 25: substitute code for overlaydocument.xul let's open base.xul in a firefox window again. as shown in figure 20, the style attribute from the element with the id "box1" in the overlay document has been merged with the markup for the button with that id in the base document, and inserted into the box. figure 20: output fr...
...ting 25: substitute code for overlaydocument.xul let's open base.xul in a firefox window again. as shown in figure 20, the style attribute from the element with the id "box1" in the overlay document has been merged with the markup for the button with that id in the base document, and inserted into the box. figure 20: output from listing 23 and 25 furthermore, following the declaration insertbefore="label1", the "button2" button now has been inserted before the element with the id "label1". conversely, if we wanted to insert it directly after, we could have used the attribute insertafter. we can also use the position attribute as a way to locate an element numerically at any position; for example, using position="4" would insert it as the fourth element. external entities being a form of ...
Appendix F: Monitoring DOM changes - Archive of obsolete content
nt identifier (hash) or more recently via the history.pushstate method. the former triggers a hashchange event while the latter triggers a popstate event. event listeners for those events are the preferred method for detecting dom modifications when feasible. often times, this must be used in combination with a slight delay, or even polling, via settimeout, for cases where the url change happens before the page is fully loaded. this method works particularly well with services like google instant, and the gawker family of sites. network listeners ajax-based page changes are almost universally tied to xmlhttprequests. these requests can be tracked from chrome code using a variety of methods, including web progress listeners, http observers, and content policies. while these are not exceptiona...
...observers, and content policies. while these are not exceptionally efficient (they run for every http request, and considerably more often for some methods), they work very well for certain applications pure css pure css can be more powerful than most people suspect. it is often possible to do things for which people have traditionally resorted to javascript with css alone. in particular, the ::before and ::after pseudo-elements, and pseudo-classes like :hover and :active can be used to achieve extremely complex dynamic behavior. late binding and event delegation often times, it suffices to bind event listeners to top-level elements and check for matching elements when the event fires. for instance, rather than watching for the creation of <a> elements and adding event listeners to them as t...
... doawesomerdomstuff(res, arguments); return res; }; } now, whenever doawesomedomstuff() is called, the original function will be called, followed by your own doawesomerdomstuff() function, which can then further modify the dom as needed. 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. 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...
... ...
Extensions support in SeaMonkey 2 - Archive of obsolete content
f you add your own. ordinary popups are fine of course. the statusbar in firefox 3 a new vbox has been added, called "browser-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. ...
... a new vbox has been added, called "browser-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. ...
... display, it may affect your extension if it overlays chrome relative to these elements. ...
...it overlays chrome relative to these elements. ...
Session store API - Archive of obsolete content
interfaces.nsiconsoleservice) .logstringmessage("restoring tab: " + uri); }; document.addeventlistener("sstabrestoring", myextensionhandlerestore, false); simply replace the contents of the function myextensionhandlerestore() with whatever you need to do when the tab is restored. in this example, nsiconsoleservice is used to display a message to the console. ...
... restoring without restarting firefox 3.6 note this section applies to firefox 3.6 and later. firefox 3.6 knows how to save session store data when the last browser window closes, even if there are still other windows open. ...
...ab'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 loading, text fields and scroll state are restored. finally, the sstabrestored event is sent. if you want to set permissions or otherwise manipulate a restored tab before the page is loaded into it, you should watch sstabrestoring. if you want to do something after the page is loaded, you should watch sstabrestored. both events are always sent for each tab being restored. you can determine which tab is being restored by looking at the event's originaltarget field. there's not really a way to determine when the last tab has been restored unless you determine how ...
...s["@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 reading session store data and before using it, as well as immediately before writing it back to disk. see the list in observer notifications. using the session store api in seamonkey there are a number of differences between the session store api in firefox and the api in seamonkey 2.0: the class name is @mozilla.org/suite/sessionstore;1 var ss = components.classes["@mozilla.org/suite/sessionstore;1"] .gets...
Developing New Mozilla Features - Archive of obsolete content
and of course, we have a set of coding practices to help everyone live together. ...
...and of course, we have a set of coding practices to help everyone live together. life will be much easier if your team has one or more members who are already familiar with and to the mozilla world. ...
...equent patches, so much the better. if you think your feature can only be implemented and reviewed in one enormous chunk, ask for design help in the appropriate newsgroup and/or from the developers with whom you have established relationships. if it is not possible to submit your feature in manageable size patches and you submit a 500k patch, be prepared for several months of review and revision before the patch is ready to be checked in it may not take this long. but if your team has worked for months on a feature, it is going to take reviewers new to the code a long time to work their way through it. and if it’s not possible to design the feature in bite-size chunks, it probably won’t be possible to review it that way either. we expect our reviewers to understand the code they approve fo...
...s a good contact for project management discussions. let us know what you’re doing. if you can find the resources, designate someone on your team as the liaison to mozilla.org for project management issues. review and super-review take time improving the code as requested by the reviewers takes time. poor quality code also takes time. we’ve opted to spend the time improving code consistency before check-in when the pain is limited to the developers and the reviewers rather than everyone in the tree. we’re committed to this style of development, but recognize that vigilance is necessary to make sure newcomers and their features don’t get lost. if you’re having a particularly bad experience or if you’ve got suggestions on how to improve our process, please let mozilla.org staff know.
Creating XPI Installer Modules - Archive of obsolete content
tents of the archive to mozilla's chrome registry; as long as the explanation is accurate, the contents can be arranged in almost any way you want. in the package you create in this tutorial, for example, all of the resources are located under the content/ subdirectory, but they could just as easily have been archived directly at the top--along with skin and locale resources, if you wanted. ...
... manifest.rdf file described the resources in an entire package directory or archive, now contents.rdf files can be used for as large or as small a part of your package description as you want; you can use several contents.rdf files in your package to describe the various parts (e.g., one for the skin of your package, another for the content, and so on), or you can use a single one, as was common before. mozilla is alerted to these content specifications and the resources they manage either through registration as part of an installation process (as described in this tutorial) or by way of a shortcut file called installed-chrome.txt, in which developers can point at their new contents.rdf files and have them registered as they develop (a process we do not describe here). one way of another, the ...
...h a couple of buttons and an image element. one of the buttons, labeled "show aphids", displays an alert dialog by calling a function defined in the javascript file barley.js. since we are not updating the mozilla ui to provide special access to this window (e.g., an item in the tasks menu or elsewhere), the measure of the success of the installation of the barley package is that the user can, as before, invoke our software by using a special startup option: mozilla -chrome chrome://barley/content this option tells mozilla to load a chrome other than the default, which is the main browser window. 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, w...
... of the xul file does not refer to any new skin, but imports communicator.css to make use of that skin's basic widget styles. the javascript file barley.js contains a single function, bar(), defined as follows: function bar() { alert("aphids"); } if you want to use the same gif image that is used in the barley package, it can be grabbed from here. while you are developing these resources and before you have made them a package of their own, you can test the basic layout and functionality by opening barley.xul from within mozilla by using file -> open. though mozilla will not display the file as a separate window (much less interpret it as a separate package), you ought to be able to see the image and the javascript function working as defined in barley.js (provided that both all three files...
Attribute (XUL) - Archive of obsolete content
« xul reference home acceltext accessible accesskey activetitlebarcolor afterselected align allowevents allownegativeassertions alternatingbackground alwaysopenpopup attribute autocheck autocompleteenabled autocompletepopup autocompletesearch autocompletesearchparam autofill autofillaftermatch autoscroll beforeselected buttonaccesskeyaccept buttonaccesskeycancel buttonaccesskeydisclosure buttonaccesskeyextra1 buttonaccesskeyextra2 buttonaccesskeyhelp buttonalign buttondir buttondisabledaccept buttonlabelaccept buttonlabelcancel buttonlabeldisclosure buttonlabelextra1 buttonlabelextra2 buttonlabelhelp buttonorient buttonpack buttons checked checkstate clicktoscroll class closebutton closemenu coalesceduplicatearcs collapse collapsed colo...
...xed flags flex focused forcecomplete grippyhidden grippytooltiptext group handlectrltab height helpuri hidden hidechrome hidecolumnpicker hideheader hideseconds hidespinbuttons highlightnonmatches homepage href icon id ignoreblurwhilesearching ignorecase ignoreincolumnpicker ignorekeys image inactivetitlebarcolor increment index inputtooltiptext insertafter insertbefore instantapply inverted iscontainer isempty key keycode keytext label lastpage lastselected last-tab left linkedpanel max maxheight maxlength maxpos maxrows maxwidth member menu menuactive min minheight minresultsforpopup minwidth mode modifiers mousethrough movetoclick multiline multiple name negate newlines next noautofocus noautohide noinitialfocus nomatc...
...isempty key keycode keytext label lastpage lastselected last-tab left linkedpanel max maxheight maxlength maxpos maxrows maxwidth member menu menuactive min minheight minresultsforpopup minwidth mode modifiers mousethrough movetoclick multiline multiple name negate newlines next noautofocus noautohide noinitialfocus nomatch norestorefocus object observes onbeforeaccept onbookmarkgroup onchange onclick onclosetab oncommand oncommandupdate ondialogaccept ondialogcancel ondialogclosure ondialogextra1 ondialogextra2 ondialoghelp onerror onerrorcommand onextra1 onextra2 oninput onload onnewtab onpageadvanced onpagehide onpagerewound onpageshow onpaneload onpopuphidden onpopuphiding onpopupshowing onpopupshown onsearchcomplete onse...
...ontextrevert ontextreverted onunload onwizardback onwizardcancel onwizardfinish onwizardnext open ordinal orient pack pageid pageincrement pagestep parent parsetype persist persistence phase pickertooltiptext placeholder popup position predicate preference preference-editable primary priority properties querytype readonly ref rel removeelement resizeafter resizebefore rows screenx screeny searchbutton searchsessions searchlabel selected selectedindex seltype setfocus showcaret showcommentcolumn showpopup size sizemode sizetopopup smoothscroll sort sortactive sortdirection sortresource sortresource2 spellcheck src state statedatasource statusbar statustext style subject substate suppressonselect tabindex tabscrolling targets ...
findbar - Archive of obsolete content
xamples | attributes | properties | methods | related ] in gecko 1.9, the findbar widget moved into toolkit, so it's available to any xul application, as well as extensions. for example, the standard findbar in firefox 3.5 looks like this on the mac: you may attach a findbar to a particular browser element by either setting the findbar's browserid attribute to the id of the browser element before the findbar element is bound, or by setting the findbar's browser property to the browser element itself. attributes browserid, findnextaccesskey, findpreviousaccesskey, highlightaccesskey, matchcaseaccesskey properties browser, findmode methods close, onfindagaincommand, open, startfind, togglehighlight example <browser type="content-primary" flex="1" ...
...aredocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), removeattributenode(), removeattributens(), removechild(), removeeventlistener(), replacechild(), setattribute(), setattributenode(), setattributenodens(), setattributens(), setuserdata close() return type: no return value ...
...close() return type: no return value closes the notification or findbar and removes it from its enclosing notificationbox or findbar. open( mode ) return type: no return value opens the findbar using the specified mode, which should be one of find_normal, find_typeahead, or find_links. if you don't pass a mode, the last-used mode for the same findbar is used. if the findbar hasn't been used before, find_normal is the default. onfindagaincommand( findprevious ) return type: no return value call this method to handle your application's "find next" and "find previous" commands. you should specify true as the input parameter to perform a "find previous" operation, or false to perform a "find next." startfind( mode ) return type: no return value call this method to handle your application'...
...on's "find" command. this opens the findbar, focuses the edit field for the search term, and selects its contents. the first time this is called for a given findbar, the findbar will flash to draw attention to itself. the mode should be one of find_normal, find_typeahead, or find_links. if you don't pass a mode, the last-used mode for the same findbar is used. if the findbar hasn't been used before, find_normal is the default. togglehighlight( highlight ) return type: no return value turns highlighting of text matching the search term on and off; specify false to disable highlighting or true to enable it. ...
insertItem - Archive of obsolete content
the third argument can be used to wrap the new item in another element. usually, the last argument will be null as it is mainly for the use of the customize dialog. the id should match an element in the toolbar's toolbarpalette. ...
...the third argument can be used to wrap the new item in another element. usually, the last argument will be null as it is mainly for the use of the customize dialog. the id should match an element in the toolbar's toolbarpalette. ...
...the third argument can be used to wrap the new item in another element. usually, the last argument will be null as it is mainly for the use of the customize dialog. the id should match an element in the toolbar's toolbarpalette. ...
...the third argument can be used to wrap the new item in another element. usually, the last argument will be null as it is mainly for the use of the customize dialog. the id should match an element in the toolbar's toolbarpalette. ...
Extensions - Archive of obsolete content
adding a new menu the main menu bar in firefox has the id 'main-menubar'. to add a new menu onto the main application menubar, you will need to overlay this menubar. for instance: <menubar id="main-menubar"> <menu label="search" insertbefore="tools-menu"> <menupopup> <menuitem label="web"/> <menuitem label="mail"/> </menupopup> </menu> </menubar> this menu is added to the main menu bar just before the tools menu. the insertbefore attribute is set to 'tools-menu' 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 fi...
...to append the item to. for a list of the ids of the menus for firefox, see firefox menus. for example, to add an item to the end of the tools menu, use the following: <menupopup id="menu_toolspopup"> <menuitem label="thesaurus"/> </menupopup> note that other extensions may be adding their own items into the same menus. because of this, the new item might not appear at the end of the menu but before a menuitem added by another extension, depending on the order in which the overlays are applied. as you cannot predict this order, you should not rely on any menuitems being in particular positions in the presence of other extensions. modifying the context menu an extension may wish to modify the context menu associated with the browser area. normally, this menu displays menu items specific to ...
...="thumbnail-show" label="view thumbnail" oncommand="thumbnails.view();"/> </popup> note that the popup element is used rather than the menupopup element as this is the element that firefox uses. the code above will append the new item at the end of the context menu. if you want to place the item at a specific location within the context menu rather than at the end, you can use either the insertbefore or insertafter attributes to insert it before or after another item specified by an id. for example, the following may be used to insert a command just after the 'select all' command: <popup id="contentareacontextmenu"> <menuitem label="select links" oncommand="thumbnails.selectalllinks();" insertafter="context-selectall"/> </popup> see firefox context menu for a list of the ids ...
...in this example, the thumbnailsshowhideitems function will be called when the popup is about to be shown. this function retrieves the menuitem with the id 'thumbnail-show' that was added by the extension and hides it if an image was not the target of the context menu. the popupnode property of the document holds the target of the context menu. for more details abo...
Localization - Archive of obsolete content
will occur as it won't be able to find the entities. to do this, add a line of the following form somewhere near the top of the xul file: <!doctype window system "chrome://findfile/locale/findfile.dtd"> this line specifies that the url indicated is to be used as a dtd for the file. in this case, we have declared that we want to use the findfile.dtd dtd file. this line is typically placed just before the window element. you also need to add the locale to the chrome.manifest file, for example: locale findfile en-us locale/ declaring entities the entities are declared using a simple syntax as shown below: <!entity findlabel "find"> this example creates an entity with the name findlabel and the value "find". this means that wherever the text "&findlabel;" appears in the xul file, it will...
...play: none;" flex="1"> <treecols> <treecol id="name" label="&results.filename;" flex="1"/> <treecol id="location" label="&results.location;" flex="2"/> <treecol id="size" label="&results.size;" flex="1"/> </treecols> <treechildren> <treeitem> <treerow> <treecell label="mozilla"/> <treecell label="/usr/local"/> <treecell label="&bytes.before;2520&bytes.after;"/> </treerow> </treeitem> </treechildren> </tree> <splitter id="splitbar" resizeafter="grow" style="display: none;"/> <spacer class="titlespace"/> <hbox> <progressmeter id="progmeter" value="50%" style="display: none;"/> <spacer flex="1"/> <button id="find-button" label="&button.find;" oncommand="dofind()"/> <button id="cancel-button"...
... is not important. in the example above, words in entities have been separated with periods. you don't have to do this. the entity names here follow similar conventions as the rest of the mozilla code. you might notice that the text '2520 bytes' has been replaced by two entities. this is because the phrase structure may be different in another locale. for example, the number might need to appear before the equivalent of 'bytes' instead of after. of course, this might need to be more complicated in order to display kb or mb as needed. the access keys and keyboard shortcuts have also been translated into entities because they will likely be different in a different locale. next, the dtd file - findfile.dtd: <!entity findwindow.title "find files"> <!entity filemenu.label "file"> <!entity editme...
...by using the chrome system to add the dtd file to a different locale, the same xul file can be used in any language. find files example so far: source next, we'll look at property files. « previousnext » ...
datepicker - Archive of obsolete content
value type: string the initial value of the datepicker in the form yyyy-mm-dd. properties date type: integer the currently selected date of the month from 1 to 31. set this property to change the selected date. dateleadingzero type: boolean a read only value indicating whether a leading zero should be displayed before the date when it is less than 10. datevalue type: date the date that is currently entered or selected in the datepicker as a date object. disabled type: boolean gets and sets the value of the disabled attribute. month type: integer the currently selected month from 0 to 11. set this property to change the selected month. ...
...ed in the datepicker as a date object. disabled type: boolean gets and sets the value of the disabled attribute. month type: integer the currently selected month from 0 to 11. set this property to change the selected month. monthleadingzero type: boolean a read only value indicating whether a leading zero should be displayed before the month when it is less than 10. open type: boolean for popup type datepickers, specifies whether the popup is open. set this property to open or close the popup. for non-popup datepickers, this property is always false. readonly type: boolean if set to true, then the user cannot modify the value of the element. tabindex type: int...
...in the form yyyy-mm-dd. unlike the month property, months in this value range from 01 to 12. set this property to change the selected date. year type: integer the currently selected year from 1 to 9999. set this property to change the selected year. yearleadingzero type: boolean a read only value indicating whether a leading zero should be displayed before the year when it is less than 1000. methods inherited methods addeventlistener(), appendchild(), blur, click, clonenode(), comparedocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbyt...
...aredocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), removeattributenode(), removeattributens(), removechild(), removeeventlistener(), replacechild(), setattribute(), setattributenode(), setattributenodens(), setattributens(), setuserdata related interfaces nsidomxulcontrole...
menupopup - Archive of obsolete content
enu id="submenu2" label="submenu 1"> <menupopup id="submenu2-popup"> <menuitem label="submenu2 item 1"/> <menuitem label="submenu2 item 2"/> </menupopup> </menu> <menupopup/> onpopuphiding type: script code this event is sent to a popup when it is about to be hidden. onpopupshowing type: script code this event is sent to a popup just before it is opened. this handler is usually used to dynamically set the contents when the user requests to display it. returning false from this event handler prevents the popup from appearing. onpopupshown type: script code this event is sent to a popup after it has been opened, much like the onload event is sent to a window when it is opened. position type: string the position attri...
... second word). the anchor value (ie, the first word) can be one of topleft, topright, bottomleft, bottomright, leftcenter, rightcenter, topcenter or bottomcenter. the popup value (ie, the second word) can be one of topleft, topright, bottomleft or bottomright. positions specified as a single word string are shortcuts for the values above. valid single-word values are after_start, after_end, before_start, before_end, end_after, end_before, start_after, start_before, overlap, at_pointer or after_pointer. for more details, including examples, please see popup positioning top type: integer overrides the vertical position of the popup specified by the showpopup method. properties accessibletype type: integer a value indicating the type of accessibility ob...
...node(), comparedocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), removeattributenode(), removeattributens(), removechild(), removeeventlistener(), replacechild(), setattribute(), setattributenode(), setattributenodens(), setattributens(), setuserdata hidepopup() return type: ...
...supply an anchor node and set the position to a string indicating the manner in which the popup should be anchored. the anchor node does not need to be in the same document as the popup. unanchored popups may be created by supplying null as the anchor node. the direction in which the popup is oriented depends on the direction of the anchor. position possible values for position are: before_start, before_end, after_start, after_end, start_before, start_after, end_before, end_after, overlap, and after_pointer. check positioning of the popup guide for a precise description of the effect of the different values. x, y for an anchored popup, the x and y arguments may be used to offset the popup from its anchored position by some number, measured in css pixels. an unanchored...
prefwindow - Archive of obsolete content
tcher.openwindow() with a null parentwindow. this does not work with prefwindows, breaking the general behavior of the window and in particular the list of prefpanes. prefer the classical window.opendialog() with the following window features: "chrome,titlebar,toolbar,centerscreen,dialog=yes". ...
.... 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. lastselected type: string set this to the id of the last selected pane. it will be opened by default the next time the preferences dialog is opened. onbeforeaccept type: script code the code in this attribute is called when the ok button is pressed or the acceptdialog method is called. returning false doesn't currently prevent the dialog from closing, but does prevent saving (bug 474527). ondialogaccept type: script code the code in this attribute is called when the accept button is pressed, or when the acceptdialog method is called. if th...
...node(), comparedocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), removeattributenode(), removeattributens(), removechild(), removeeventlistener(), replacechild(), setattribute(), setattributenode(), setattributenodens(), setattributens(), setuserdata acceptdialog() return type...
...opened via document.documentelement and not via window. therefore, an example call to opensubdialog() would look like this: document.documentelement.opensubdialog("chrome://myextension/content/options-sub.xul", "", null) issues when using prefpanes in prefwindow when you wish to put non-<prefpane> elements to prefwindow, you should place them after all of <prefpane>s. if you put other elements before the first <prefpane>, you possibly see strange behaviors about switching panes. this is due to bug 296418. should not: <prefwindow> <script src="config.js"/> <prefpane label="pane1" src="pane1.xul"/> <prefpane label="pane2" src="pane2.xul"/> </prefwindow> should: <prefwindow> <prefpane label="pane1" src="pane1.xul"/> <prefpane label="pane2" src="pane2.xul"/> <script src="config.j...
timepicker - Archive of obsolete content
he value of the disabled attribute. hideseconds type: boolean indicates whether the seconds field is visible or not. hour type: integer the currently selected hour from 0 to 23. set this property to change the selected hour. hourleadingzero type: boolean a read only value indicating whether a leading zero should be displayed before the hour when it is less than 10. increment type: integer gets and sets the value of the increment attribute. is24hourclock type: boolean a read only value indicating whether a 12-hour or 24-hour clock is used to display times. with a 12-hour clock, an extra field allows the user to pick between am and pm. this value is determined from the user's lo...
...'s locale. ispm type: boolean if false, the hour is between 0 and 11, and if true, the hour is 12 or greater. minute type: integer the currently selected minute from 0 to 59. set this property to change the selected minute. minuteleadingzero type: boolean a read only value indicating whether a leading zero should be displayed before the minute when it is less than 10. pmindicator type: string the string value displayed for hours between noon and midnight, defaulting to pm. this value is determined from the user's locale. readonly type: boolean if set to true, then the user cannot modify the value of the element. second type: integer the currently selecte...
...e user's locale. readonly type: boolean if set to true, then the user cannot modify the value of the element. second type: integer the currently selected second from 0 to 59. set this property to change the selected second. secondleadingzero type: boolean a read only value indicating whether a leading zero should be displayed before the second when it is less than 10. tabindex type: integer gets and sets the value of the tabindex attribute. value type: string the currently entered time of the form hh:mm:ss. set this property to change the time. methods inherited methods addeventlistener(), appendchild(), blur, click, clonenode(), comparedocumentposition, dispatchevent(),...
...aredocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), removeattributenode(), removeattributens(), removechild(), removeeventlistener(), replacechild(), setattribute(), setattributenode(), setattributenodens(), setattributens(), setuserdata related interfaces nsidomxulcontrol...
toolbar - Archive of obsolete content
he id of the toolbox this toolbar is a member of. this will either be the toolbox's parent (if it's in a toolbox), or, if the toolbar is an external toolbar (that is, one not contained in a toolbox), the id of the toolbox it should be considered to be part of. this makes it possible to have toolbars that are not contained within toolboxes, such as the add-on bar. ...
...this toolbar is a member of. this will either be the toolbox's parent (if it's in a toolbox), or, if the toolbar is an external toolbar (that is, one not contained in a toolbox), the id of the toolbox it should be considered to be part of. this makes it possible to have toolbars that are not contained within toolboxes, such as the add-on bar. ...
...(that is, one not contained in a toolbox), the id of the toolbox it should be considered to be part of. this makes it possible to have toolbars that are not contained within toolboxes, such as the add-on bar. methods insertitem( id, beforenode, wrapper, beforepermanent ) not in seamonkey 1.x return type: element add an item with the given id to the toolbar. the new item is added just before the item given by the second argument. if the second argument is null, but the beforepermanent argument is true, the item is added to the beginning of the toolbar before the first permanent item. otherwise, if the beforepermanent argument is false, the new item is added to the end of the toolbar. the third argument can be used to wrap the new item in another element. usually, the last argument wi...
...aredocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), removeattributenode(), removeattributens(), removechild(), removeeventlistener(), replacechild(), setattribute(), setattributenode(), setattributenodens(), setattributens(), setuserdata style classes chromeclass-t...
tooltip - Archive of obsolete content
<menu id="submenu2" label="submenu 1"> <menupopup id="submenu2-popup"> <menuitem label="submenu2 item 1"/> <menuitem label="submenu2 item 2"/> </menupopup> </menu> <menupopup/> onpopuphiding type: script code this event is sent to a popup when it is about to be hidden. onpopupshowing type: script code this event is sent to a popup just before it is opened. this handler is usually used to dynamically set the contents when the user requests to display it. returning false from this event handler prevents the popup from appearing. onpopupshown type: script code this event is sent to a popup after it has been opened, much like the onload event is sent to a window when it is opened. page type: boolean setting the pag...
... second word). the anchor value (ie, the first word) can be one of topleft, topright, bottomleft, bottomright, leftcenter, rightcenter, topcenter or bottomcenter. the popup value (ie, the second word) can be one of topleft, topright, bottomleft or bottomright. positions specified as a single word string are shortcuts for the values above. valid single-word values are after_start, after_end, before_start, before_end, end_after, end_before, start_after, start_before, overlap, at_pointer or after_pointer. for more details, including examples, please see popup positioning properties accessibletype type: integer a value indicating the type of accessibility object for the element. label type: string gets and sets the value of the label attribut...
...node(), comparedocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), removeattributenode(), removeattributens(), removechild(), removeeventlistener(), replacechild(), setattribute(), setattributenode(), setattributenodens(), setattributens(), setuserdata hidepopup() return type: n...
...supply an anchor node and set the position to a string indicating the manner in which the popup should be anchored. the anchor node does not need to be in the same document as the popup. unanchored popups may be created by supplying null as the anchor node. the direction in which the popup is oriented depends on the direction of the anchor. position possible values for position are: before_start, before_end, after_start, after_end, start_before, start_after, end_before, end_after, overlap, and after_pointer. check positioning of the popup guide for a precise description of the effect of the different values. x, y for an anchored popup, the x and y arguments may be used to offset the popup from its anchored position by some number, measured in css pixels. an unanchored...
where - Archive of obsolete content
Archive › Mozilla › XUL › where
should be reversed. the where clause matches if the condition is false, and does not match if the condition is true. rel type: one of the values below the type of comparison to perform. equals the subject and value must match exactly. ...
... the condition is false, and does not match if the condition is true. rel type: one of the values below the type of comparison to perform. equals the subject and value must match exactly. less the numeric value of the subject must be less than the value greater the numeric value of the subject must be greater than the value before the string value of subject must come before value alphabetically after the string value of subject must come after value alphabetically 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 c...
...in the value as a substring subject type: string the variable or string to compare. value type: string the value to compare. ...
...aredocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), removeattributenode(), removeattributens(), removechild(), removeeventlistener(), replacechild(), setattribute(), setattributenode(), setattributenodens(), setattributens(), setuserdata ...
Sunbird Theme Tutorial - Archive of obsolete content
erent icons on the buttons. but a theme cannot provide an extra button. what do you need to make a theme? to make a theme, you usually need these tools: a jar tool or zip tool an editor for plain text files software for creating and editing images note: some zip tools only work with files whose names have <tt>.zip</tt> at the end. you can use this kind of zip tool if you rename each file before and after using the tool. you also need knowledge of: using your operating system to create files and directories using the tools listed above css graphic design knowledge of xul, xbl and javascript is useful for advanced themes. making a theme a theme consists of: a unique identifier a file containing information about the theme a file that registers the theme with sunbird some fil...
...if the <tt>extensions</tt> directory is empty, you are in the wrong place—start again and follow the instructions more carefully. creating a unique identifier create an identifier that is likely to be unique, in the form: <tt>something@domain-name</tt> it must contain an at-sign (<tt>@</tt>), making it look something like an e-mail address, but it does not need to be a real e-mail address. before and after the at-sign, it can only contain the characters a-z, a-z, 0-9, full stop, hyphen and underscore. if you do not own a domain name, you can make up something else. if you want to make it clear that your made-up name is not a real domain, add <tt>.invalid</tt> to the end. create a new directory in the <tt>extensions</tt> directory. use the identifer as your new directory's name. this new d...
...as sunbird's classic theme. modifying your theme to modify your theme, change the css and image files in any way you like. for testing purposes, go to the <tt>calendar</tt> directory that you have just pasted. edit the file <tt>calendar.css</tt> there. add this line at the end: label {color: red;} save the file. fixing bug 320823 if you are using the sunbird 0.3a1 release, or a test build before 2005-12-21, then you must apply a fix for bug 320823 to allow sunbird to use themes. go to sunbird's program directory, then to the <tt>defaults</tt> directory there. in the <tt>pref</tt> directory, edit the file <tt>sunbird.js</tt> and search for the <tt>pref("extensions</tt> entries. add the line: pref("extensions.dss.enabled", false); save the file. using your theme to use your theme, res...
...hrome</tt> directory. from the unpacked <tt>skin/classic</tt> directory, copy the extra directories into your theme. in your <tt>chrome.manifest</tt> file, add lines like this: skin communicator testing chrome/communicator/ skin global testing chrome/global/ skin help testing chrome/help/ skin mozapps testing chrome/mozapps/ replacing <tt>testing</tt> with your theme's one-word internal name as before. to understand the user interface provided by these other components, unpack the other jar files. packaging your theme you can package your theme and make it available on a web site for other users to download and install. there are two methods: a simple method, and the normal method. simple packaging note: if you use this simple method to package your theme, then it can take up much more ...
Browser Feature Detection - Archive of obsolete content
e bottom true true true captionside true false true clear true true true clip true true true content true false true counterincrement true false true counterreset true false true cue true false false cueafter true false false cuebefore true false false cursor true true true direction true true true elevation true false false emptycells true false true fontsizeadjust true false true fontstretch true false true left true true true markeroffset true false true marks tr...
... true ie7 only true orphans true false true outline true false true outlinecolor true false true outlinestyle true false true outlinewidth true false true overflow true true true page true false true pagebreakafter true true true pagebreakbefore true true true pagebreakinside true false true pause true false true pauseafter true false true pausebefore true false true pitch true false false pitchrange true false true playduring false false false position true true true quotes ...
... false}, {name: 'bottom', 'supported': false}, {name: 'captionside', 'supported': false}, {name: 'clear', 'supported': false}, {name: 'clip', 'supported': false}, {name: 'content', 'supported': false}, {name: 'counterincrement', 'supported': false}, {name: 'counterreset', 'supported': false}, {name: 'cue', 'supported': false}, {name: 'cueafter', 'supported': false}, {name: 'cuebefore', 'supported': false}, {name: 'cursor', 'supported': false}, {name: 'direction', 'supported': false}, {name: 'elevation', 'supported': false}, {name: 'emptycells', 'supported': false}, {name: 'fontsizeadjust', 'supported': false}, {name: 'fontstretch', 'supported': false}, {name: 'left', 'supported': false}, {name: 'markeroffset', 'supported': false}, {name: 'marks', 'supported'...
...'minwidth', 'supported': false}, {name: 'orphans', 'supported': false}, {name: 'outline', 'supported': false}, {name: 'outlinecolor', 'supported': false}, {name: 'outlinestyle', 'supported': false}, {name: 'outlinewidth', 'supported': false}, {name: 'overflow', 'supported': false}, {name: 'page', 'supported': false}, {name: 'pagebreakafter', 'supported': false}, {name: 'pagebreakbefore', 'supported': false}, {name: 'pagebreakinside', 'supported': false}, {name: 'pause', 'supported': false}, {name: 'pauseafter', 'supported': false}, {name: 'pausebefore', 'supported': false}, {name: 'pitch', 'supported': false}, {name: 'pitchrange', 'supported': false}, {name: 'playduring', 'supported': false}, {name: 'position', 'supported': false}, {name: 'quotes', 'supported'...
Anatomy of a video game - Game development
, 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 callback function will be executed at a suitable time before the next repaint. here is an example of a simple main loop: window.main = function () { window.requestanimationframe( main ); // whatever your main loop needs to do }; main(); // start the cycle note: in each of the main() methods discussed here, we schedule a new requestanimationframe before performing our loop contents. that is not by accident and it is considered best practice. callin...
...ction does some work and also tells the browser to call itself next frame with window.requestanimationframe(). the second statement calls the main() function, defined in the first statement. because main() is called once in the second statement and every call of it places itself in the queue of things to do next frame, main() is synchronized to your framerate. of course this loop is not perfect. before we discuss ways to change it, let us discuss what it already does well. timing the main loop to when the browser paints to the display allows you to run your loop as frequently as the browser wants to paint. you are given control over each frame of animation. it is also very simple because main() is the only function getting looped. a first person shooter (or a similar game) presents a new scene...
...occur at different rates. you will also need to consider how gracefully your game will fail if the user's system cannot keep up with the workload. let us start by assuming that you will handle user input and update the game state every time you draw. we will branch out later. note: changing how your main loop deals with time is a debugging nightmare, everywhere. think about your needs carefully before working on your main loop. what most browser games should look like if your game can hit the maximum refresh rate of any hardware you support then your job is fairly easy. you can simply update, render, and then do nothing until vsync. /* * starting with the semicolon is in case whatever line of code above this example * relied on automatic semicolon insertion (asi). the browser could acciden...
.... * * update() calculates the game state as of a given point in time. it should always * increment by ticklength. it is the authority for game state. it is passed * the domhighrestimestamp for the time it represents (which, again, is always * last update + mygame.ticklength unless a pause feature is added, etc.) * * setinitialstate() performs whatever tasks are leftover before the mainloop must run. * it is just a generic example function that you might have added. */ ;(function () { function main( tframe ) { mygame.stopmain = window.requestanimationframe( main ); var nexttick = mygame.lasttick + mygame.ticklength; var numticks = 0; // if tframe < nexttick then 0 ticks need to be updated (0 is default for numticks). // if tfram...
Building up a basic demo with PlayCanvas editor - Game development
e playcanvas editor. this can be a more pleasant working environment if you are not someone who likes to code. creating an account the playcanvas editor is free — all you have to do to begin with is register your account and login: when you first sign up, you are taken straight into the editor and given a simple starter tutorial involving editing a 3d rolling ball game. you can finish this before you continue our tutorial if you like. when you are ready to continue with our tutorial, go to your canvas homepage — for example mine is https://playcanvas.com/end3r. here's what the page looks like — you can create projects and manage them, change their settings etc. creating a new project start a brand new project by clicking on the new button: the resulting dialog box will show a few...
...ion value of -2. adding other shapes involves a very similar process to adding the box. click on the root folder in the hierarchy panel (to make sure that the new shape appears in the root, and not as a child of the box) then click on the big add entity (plus) button and select cylinder from the dropdown list — it will add a new cylinder shape to the scene. now follow the same steps as we did before when coloring the cube: create a new material using the add asset (plus) button. make sure the new material in the assets panel is selected, to bring up the entity inspector. give the material a new name, along the lines of cylindermaterial. click diffuse, then click the color picker — give it an orange color (we used ff9500.) drag and drop the cylindermaterial icon onto the cylinder obj...
...on.js. if you double click on it, you'll be moved to a code editor. as you can see, the file contains some boilerplate code already: pc.script.create('boxanimation', function (app) { // creates a new boxanimation instance var boxanimation = function (entity) { this.entity = entity; }; boxanimation.prototype = { // called once after all resources are loaded and before the first update initialize: function () { }, // called every frame, dt is time in seconds since last update update: function (dt) { } }; return boxanimation; }); the most interesting part is the update() function, which is where we can put any code that we want repeated on every frame. add the following line inside this function, to rotate the c...
...e the setposition() method — add the code below to the update() function: this.timer += dt; this.entity.setposition(2, math.sin(this.timer*2), 0); the position of the cone will be animated on each frame by being passed the math.sin() value of the timer at each point in time — we have doubled the this.timer value to make it move higher. add the coneanimation.js script to the cone object, as before. test the demo out launch the demo to see the effects — all the shapes should animate. congratulations, you've completed the tutorial! summary now you can check the playcanvas engine article if you haven't seen it yet, go back to the building up a basic demo with playcanvas page, or go back a level higher to the main 3d games on the web page. ...
Plug-in Development Overview - Gecko Plugin API Reference
", string 4: "aiff audio", and string 5: "jpeg image format." str#' 126: string 1 can contain a descriptive message about the plug-in. this message, which is in html format, is displayed by the browser in its "about plug-ins" page. string 2 can contain the name of the plug-in, thus allowing the name the user sees to be different from the name of the file on disk. ...
... the browser calls these plug-in methods: npp_getvalue: query the plug-in for information. npp_print: request a platform-specific print operation for the instance. npp_setvalue: set the browser information. ...
...set the window or other target in which it draws, arrange for redrawing, and handle events. a windowless plug-in can call the following netscape methods to draw itself: npn_forceredraw: force a paint message for windowless plug-ins. npn_invalidaterect: invalidate an area in a windowless plug-in before repainting or refreshing. npn_invalidateregion: invalidate an area in a windowless plug-in before repainting or refreshing. the browser calls these plug-in methods: npp_getvalue: query the plug-in for information. npp_print: request a platform-specific print operation for the instance. npp_setvalue: set the browser information. npp_setwindow: set the window in which a plug-in draws. npp_handleevent: deliver a platform-specific event to the instance. the plug-in can call these netsc...
...nformation about these processes, see drawing and event handling. handling memory plug-in developers can take advantage of the memory features provided in the plug-in api to allocate and free memory. use the npn_memalloc method to allocate memory from the browser. use the npn_memfree method to free memory allocated with npn_memalloc. use the npn_memflush method to free memory (mac os only) before calling memory-intensive mac toolbox calls. sending and receiving streams streams are objects that represent urls and the data they contain. a stream is associated with a specific instance of a plug-in, but a plug-in can have more than one stream per instance. streams can be produced by the browser and consumed by a plug-in instance, or produced by an instance and consumed by the browser. each...
Grids - Learn web development
ifferent positive values to your tracks, for example if you change the definition like so: .container { display: grid; grid-template-columns: 2fr 1fr 1fr; } the first track now gets 2fr of the available space and the other two tracks get 1fr, making the first track larger. you can mix fr units and fixed length tracks — in such a case the space needed for the fixed tracks is taken away before the space is distributed to the other tracks. simple grid example with fr units body { width: 90%; max-width: 900px; margin: 2em auto; font: .9em/1.2 arial, helvetica, sans-serif; } .container { display: grid; grid-template-columns: 2fr 1fr 1fr; } .container > div { border-radius: 5px; padding: 10px; background-color: rgb(207,232,220); border: 2px solid rgb(79,185,227); ...
...letproof. .container { display: grid; grid-template-columns: 2fr 1fr 1fr; grid-gap: 20px; gap: 20px; } repeating track listings you can repeat all, or a section of, your track listing using repeat notation. change your track listing to the following: .container { display: grid; grid-template-columns: repeat(3, 1fr); grid-gap: 20px; } you will now get 3 1fr tracks just as before. the first value passed to the repeat function is how many times you want the listing to repeat, while the second value is a track listing, which may be one or more tracks that you want to repeat. the implicit and explicit grid we have only specified column tracks so far, and yet rows are being created to hold our content. this is an example of the explicit versus the implicit grid. the explici...
...ollowing css. ...
...ide> <footer>contact me@mysite.com</footer> </div> if you use the firefox grid inspector to overlay the grid lines on your design, you can see how our 12 column grid works. test your skills! you've reached the end of this article, but can you remember the most important information? you can find some further tests to verify that you've retained this information before you move on — see test your skills: grids. summary in this overview we have toured the main features of css grid layout. you should be able to start using it in your designs. to dig further into the specification, read our guides to grid layout, which can be found below. see also css grid guides css grid inspector: examine grid layouts previous overview: css layout next in thi...
Using CSS generated content - Learn web development
u specify content in your stylesheet that requires translation, you have to put those parts of your stylesheet in different files and arrange for them to be linked with the appropriate language versions of your doucment. this issue does not arise if the content you specify consists of symbols or images that apply in all languages and cultures. ...
... have to put those parts of your stylesheet in different files and arrange for them to be linked with the appropriate language versions of your doucment. this issue does not arise if the content you specify consists of symbols or images that apply in all languages and cultures. examples text content css can insert text content before or after an element. to specify this, make a rule and add ::before or ::after to the selector. ...
...u specify consists of symbols or images that apply in all languages and cultures. examples text content css can insert text content before or after an element. to specify this, make a rule and add ::before or ::after to the selector. in the declaration, specify the content property with the text content as its value. html a text where i need to <span class="ref">something</span> css .ref::before { font-weight: bold; color: navy; content: "reference "; } output the character set of a stylesheet is utf-8 by default, but it can also be specified in the link, in the stylesheet itself, or in other ways. for details, see 4.4 css style sheet representation in the css specification. individual characters can also be specified by an escape mechanism that uses backslash as the escape ch...
....4 css style sheet representation in the css specification. individual characters can also be specified by an escape mechanism that uses backslash as the escape character. for example, "\265b" is the chess symbol for a black queen ♛. for details, see referring to characters not represented in a character encoding and characters and case in the css specification. image content to add an image before or after an element, you can specify the url of an image file in the value of the content property. this rule adds a space and an icon after every link that has the class glossary: html <a href="developer.mozilla.org" class="glossary">developer.mozilla.org</a> css a.glossary::after { content: " " url("https://mdn.mozillademos.org/files/16322/glossary-icon.gif"); } ...
Fundamental text and font styling - Learn web development
ntent effectively behaves like a series of inline elements, being laid out on lines adjacent to one another, and not creating line breaks until the end of the line is reached, or unless you force a line break manually using the <br> element. note: if the above paragraph leaves you feeling confused, then no matter — go back and review our box model article, to brush up on the box model theory, before carrying on. the css properties used to style text generally fall into two categories, which we'll look at separately in this article: font styles: properties that affect the font that is applied to the text, affecting what font is applied, how big it is, whether it is bold, italic, etc. text layout styles: properties that affect the spacing and other layout features of the text, allowing m...
...ndependently of its actual font size. font-stretch: switch between possible alternative stretched versions of a given font. text-underline-position: specify the position of underlines set using the text-decoration-line property underline value. text-rendering: try to perform some text rendering optimization. text layout styles: text-indent: specify how much horizontal space should be left before the beginning of the first line of the text content. text-overflow: define how overflowed content that is not displayed is signaled to users. white-space: define how whitespace and associated line breaks inside the element are handled. word-break: specify whether to break lines within words. direction: define the text direction (this depends on the language and usually it's better to let html...
...y whether to break lines within words. direction: define the text direction (this depends on the language and usually it's better to let html handle that part as it is tied to the text content.) hyphens: switch on and off hyphenation for supported languages. line-break: relax or strengthen line breaking for asian languages. text-align-last: define how the last line of a block or a line, right before a forced line break, is aligned. text-orientation: define the orientation of the text in a line. overflow-wrap: specify whether or not the browser may break lines within words in order to prevent overflow. writing-mode: define whether lines of text are laid out horizontally or vertically and the direction in which subsequent lines flow. font shorthand many font properties can also be set th...
...cle, and already did some skill testing in our active learning section, but can you remember the most important information going forward? you can find an assessment to verify that you've retained this information at the end of the module — see typesetting a community school homepage. this assessment tests all the knowledge discussed in this module, so you might want to read the other articles before moving on to it. summary we hoped you enjoyed playing with text in this article! the next article will give you all you need to know about styling html lists. overview: styling text next in this module fundamental text and font styling styling lists styling links web fonts typesetting a community school homepage ...
Learn to style HTML using CSS - Learn web development
out. for example, you can use css to alter the font, color, size, and spacing of your content, split it into multiple columns, or add animations and other decorative features. 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 you should learn the basics of html before attempting any css. we recommend that you work through our introduction to html module first. in that module, you will learn about: css, starting with the introduction to css module more advanced html modules javascript, and how to use it to add dynamic functionality to web pages once you understand the fundamentals of html, we recommend that you learn html and css at the same time, moving...
... more advanced html modules javascript, and how to use it to add dynamic functionality to web pages once you understand the fundamentals of html, we recommend that you learn html and css at the same time, moving back and forth between the two topics. this is because html is far more interesting and much more fun to learn when you apply css, and you can't really learn css without knowing html. before starting this topic, you should also be familiar with using computers and using the web passively (i.e., just looking at it, consuming the content). you should have a basic work environment set up as detailed in installing basic software and understand how to create and manage files, as detailed in dealing with files — both of which are parts of our getting started with the web complete beginne...
...he web passively (i.e., just looking at it, consuming the content). you should have a basic work environment set up as detailed in installing basic software and understand how to create and manage files, as detailed in dealing with files — both of which are parts of our getting started with the web complete beginner's module. it is recommended that you work through getting started with the web before proceeding with this topic. however, doing so isn't absolutely necessary as much of what is covered in the css basics article is also covered in our css first steps module, albeit in a lot more detail. modules this topic contains the following modules, in a suggested order for working through them. you should definitely start with the first one. css first steps css (cascading style sheets) ...
...with the language and its syntax, and got some basic experience with using it, its time to dive a bit deeper. this module looks at the cascade and inheritance, all the selector types we have available, units, sizing, styling backgrounds and borders, debugging, and lots more. the aim here is to provide you with a toolkit for writing competent css and help you understand all the essential theory, before moving on to more specific disciplines like text styling and css layout. styling text with the basics of the css language covered, the next css topic for you to concentrate on is styling text — one of the most common things you'll do with css. here we look at text styling fundamentals, including setting font, boldness, italics, line and letter spacing, drop shadows and other text features. ...
Advanced form styling - Learn web development
fferent browsers handle this in many different, often ugly ways: browser rendering firefox 71 (macos) firefox 57 (windows 10) chrome 77 (macos), safari 13, opera chrome 63 (windows 10) internet explorer 11 (windows 10) edge 16 (windows 10) using appearence: none on radios/checkboxes as we showed before, you can remove the default appearance of a checkbox or radio button altogether with appearance:none; let's take this example html: <form> <fieldset> <legend>fruit preferences</legend> <p> <label> <input type="checkbox" name="fruit-1" value="cherry"> i like cherry </label> </p> <p> <label> <input type="checkbox" name="fruit-2" value="b...
... :disabled pseudo-classes to change the appearance of our custom checkbox as its state changes: input[type="checkbox"] { position: relative; width: 1em; height: 1em; border: 1px solid gray; /* adjusts the position of the checkboxes on the text baseline */ vertical-align: -2px; /* set here so that windows' high-contrast mode can override */ color: green; } input[type="checkbox"]::before { content: "✔"; position: absolute; font-size: 1.2em; right: -1px; top: -0.3em; visibility: hidden; } input[type="checkbox"]:checked::before { /* use `visibility` instead of `display` to avoid recalculating layout */ visibility: visible; } input[type="checkbox"]:disabled { border-color: black; background: #ddd; color: gray; } you'll find more out about such pseudo-class...
...differs across browsers. it also tends to change if you increase the size of the select box, or resize in an ugly fashion. to fix this in our example we first used our old friend appearance: none to get rid of the icon altogether: select { -webkit-appearance: none; appearance: none; } we then created our own icon using generated content. ...
...st fallback html in case the script fails. there are many reasons why scripts may fail, especially in the mobile world, and you need to design your web site or app to handle these cases as well as possible. test your skills! you've reached the end of this article, but can you remember the most important information? you can find some further tests to verify that you've retained this information before you move on — see test your skills: advanced styling. bear in mind that some questions in this assessment series assume knowledge of the next article too, so you might want to work through that article first before attempting it. summary while there are still difficulties using css with html forms, there are ways to get around many of the problems. there are no clean, universal solutions, but...
Client-side form validation - Learn web development
this is called client-side form validation, and helps ensure data submitted matches the requirements set forth in the various form controls. this article leads you through basic concepts and examples of client-side form validation. prerequisites: computer literacy, a reasonable understanding of html, css, and javascript. objective: to understand what client-side form validation is, why it's important, and how to apply various techniques to implement it. ...
... need to create it all (or use a library). using built-in form validation one of the most significant features of html5 form controls is the ability to validate most user data without relying on javascript. this is done by using validation attributes on form elements. we've seen many of these earlier in the course, but to recap: required: specifies whether a form field needs to be filled in before the form can be submitted. minlength and maxlength: specifies the minimum and maximum length of textual data (strings) min and max: specifies the minimum and maximum values of numerical input types type: specifies whether the data needs to be a number, an email address, or some other specific preset type. pattern: specifies a regular expression that defines a pattern the entered data needs t...
...ton>submit</button> </form> this simple form uses the novalidate attribute to turn off the browser's automatic validation; this lets our script take control over validation. however, this doesn't disable support for the constraint validation api nor the application of css pseudo-classes like :valid, etc. that means that even though the browser doesn't automatically check the validity of the form before sending its data, you can still do it yourself and style the form accordingly. our input to validate is an <input type="email">, which is required, and has a minlength of 8 characters. let's check these using our own code, and show a custom error message for each one. we are aiming to show the error messages inside a <span> element. the aria-live attribute is set on that <span> to make sure tha...
... on your own. the difficult part is to make it generic enough to use both cross-platform and on any form you might create. there are many libraries available to perform form validation, such as validate.js. test your skills! you've reached the end of this article, but can you remember the most important information? you can find some further tests to verify that you've retained this information before you move on — see test your skills: form validation. summary client-side form validation sometimes requires javascript if you want to customize styling and error messages, but it always requires you to think carefully about the user. always remember to help your users correct the data they provide. to that end, be sure to: display explicit error messages. be permissive about the input for...
Images in HTML - Learn web development
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 depth, including the basics, annotating it with captions using <figure>, and detailing how it relates to css background images. ...
... requires a minimum of one attribute to be useful — src (sometimes spoken as its full title, source). the src attribute contains a path pointing to the image you want to embed in the page, which can be a relative or absolute url, in the same way as href attribute values in <a> elements. note: you should read a quick primer on urls and paths to refresh your memory on relative and absolute urls before continuing. so for example, if your image is called dinosaur.jpg, and it sits in the same directory as your html page, you could embed the image like so: <img src="dinosaur.jpg"> if the image was in an images subdirectory, which was inside the same directory as the html page (which google recommends for seo/indexing purposes), then you'd embed it like this: <img src="images/dinosaur.jpg"> a...
...n't alter the size of your images using html attributes. if you set the image size too big, you'll end up with images that look grainy, fuzzy, or too small, and wasting bandwidth downloading an image that is not fitting the user's needs. the image may also end up looking distorted, if you don't maintain the correct aspect ratio. you should use an image editor to put your image at the correct size before putting it on your webpage. note: if you do need to alter an image's size, you should use css instead. image titles as with links, you can also add title attributes to images, to provide further supporting information if needed. in our example, we could do this: <img src="images/dinosaur.jpg" alt="the head and torso of a dinosaur skeleton; it has a large head with long sharp ...
...in terms of your content, you should use an html image. if an image is purely decoration, you should use css background images. note: you'll learn a lot more about css background images in our css topic. test your skills! you've reached the end of this article, but can you remember the most important information? you can find some further tests to verify that you've retained this information before you move on — see test your skills: html images. summary that's all for now. we have covered images and captions in detail. in the next article we'll move it up a gear, looking at how to use html to embed video and audio in web pages. overview: multimedia and embedding next in this module images in html video and audio content from <object> to <iframe> — other embedding techno...
Responsive images - Learn web development
al size, which can be found by inspecting the image file on your computer (for example, on a mac you can select the image in finder and press cmd + i to bring up the info screen). sizes defines a set of media conditions (e.g. screen widths) and indicates what image size would be best to choose, when certain media conditions are true — these are the hints we talked about earlier. in this case, before each comma we write: a media condition ((max-width:600px)) — you'll learn more about these in the css topic, but for now let's just say that a media condition describes a possible state that the screen can be in. in this case, we are saying "when the viewport width is 600 pixels or less". a space the width of the slot the image will fill when the media condition is true (480px) note: fo...
.... just as we saw with <img> above, <source> can take a srcset attribute with multiple images referenced, as well as a sizes attribute. so, you could offer multiple images via a <picture> element, but then also offer multiple resolutions of each one. realistically, you probably won't want to do this kind of thing very often. in all cases, you must provide an <img> element, with src and alt, right before </picture>, otherwise no images will appear. this provides a default case that will apply when none of the media conditions return true (you could actually remove the second <source> element in this example), and a fallback for browsers that don't support the <picture> element. this code allows us to display a suitable image on both wide screen and narrow screen displays, as shown below: no...
...lows us to display a suitable image on both wide screen and narrow screen displays, as shown below: note: you should use the media attribute only in art direction scenarios; when you do use media, don't also offer media conditions within the sizes attribute. why can't we just do this using css or javascript? when the browser starts to load a page, it starts to download (preload) any images before the main parser has started to load and interpret the page's css and javascript. that mechanism is useful in general for reducing page load times, but it is not helpful for responsive images — hence the need to implement solutions like srcset. for example, you couldn't load the <img> element, then detect the viewport width with javascript, and then dynamically change the source image to a small...
...have fun! ...
General asynchronous programming concepts - Learn web development
prerequisites: basic computer literacy, a reasonable understanding of javascript fundamentals. objective: to understand the basic concepts behind asynchronous programming, and how they manifest in web browsers and javascript. ...
...mitigate all the time. why is this? the answer is because javascript, generally speaking, is single-threaded. at this point, we need to introduce the concept of threads. threads a thread is basically a single process that a program can use to complete tasks. each thread can only do a single task at once: task a --> task b --> task c each task will be run sequentially; a task has to complete before the next one can be started. as we said earlier, many computers now have multiple cores, so can do multiple things at once. programming languages that can support multiple threads can use multiple cores to complete multiple tasks simultaneously: thread 1: task a --> task b thread 2: task c --> task d javascript is single-threaded javascript is traditionally single-threaded. even with multiple...
... 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 it running live), again with your browser's javascript console open. this is a rewrite of our previous example that calculates the 10 million dates in a separate worker thread. now when you click the button, the browser is able to display the paragraph before the dates have finished calculating. the first operation no longer blocks the second. asynchronous code web workers are pretty useful, but they do have their limitations. a major one is they are not able to access the dom — you can'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 crunc...
...available at the same time, then we might be ok, but this is unlikely. if task d tries to run when one of its inputs is not yet available, it will throw an error. to fix such problems, browsers allow us to run certain operations asynchronously. features like promises allow you to set an operation running (e.g. the fetching of an image from the server), and then wait until the result has returned before running another operation: main thread: task a task b promise: |__async operation__| since the operation is happening somewhere else, the main thread is not blocked while the async operation is being processed. we'll start to look at how we can write asynchronous code in the next article. exciting stuff, huh? keep reading! conclusion modern software design increasi...
Introducing asynchronous JavaScript - Learn web development
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 wait until the response is returned before it tries to do anything else to it. there are two main types of asynchronous code style you'll come across in javascript code, old-style callbacks and newer promise-style code. in the below sections we'll review each of these in turn. async callbacks async callbacks are functions that are specified as arguments when calling a function which will start executing code in the background. when the...
...er, we then create a loadasset() function that takes a callback as a parameter, along with a url to fetch and a content type. it uses xmlhttprequest (often abbreviated to "xhr") to fetch the resource at the given url, then pass the response to the callback to do something with. in this case the callback is waiting on the xhr call to finish downloading the resource (using the onload event handler) before it passes it to the callback. callbacks are versatile — not only do they allow you to control the order in which functions are run and what data is passed between them, they also allow you to pass data to different functions depending on circumstance. so you could have different actions to run on the response downloaded, such as processjson(), displaytext(), etc. note that not all callbacks a...
... function will be executed when passing a callback to a third-party library. the nature of asynchronous code let's explore an example that further illustrates the nature of async code, showing what can happen when we are not fully aware of code execution order and the problems of trying to treat asynchronous code like synchronous code. the following example is fairly similar to what we've seen before (see it live, and the source). one difference is that we've included a number of console.log() statements to illustrate an order that you might think the code would execute in. console.log ('starting'); let image; fetch('coffee.jpg').then((response) => { console.log('it worked :)') return response.blob(); }).then((myblob) => { let objecturl = url.createobjecturl(myblob); image = documen...
..., except that in that case the second message is blocked on the promise chain fetching a resource then displaying it on screen, rather than a click. in a less trivial code example, this kind of setup could cause a problem — you can't include an async code block that returns a result, which you then rely on later in a sync code block. you just can't guarantee that the async function will return before the browser has processed the sync block. to see this in action, try taking a local copy of our example, and changing the fourth console.log() call to the following: console.log ('all done! ' + image.src + 'displayed.'); you should now get an error in your console instead of the third message: typeerror: image is undefined; can't access its "src" property this is because at the time the brow...
What went wrong? Troubleshooting JavaScript - Learn web development
ogic somewhere — the game is not returning an error; it just isn't playing right. search for the randomnumber variable, and the lines where the random number is first set. ...
.... 0.5675493843. math.random() next, we pass the result of invoking math.random() through math.floor(), which rounds the number passed to it down to the nearest whole number. we then add 1 to that result: math.floor(math.random()) + 1 rounding a random decimal number between 0 and 1 down will always return 0, so adding 1 to it will always return 1. we need to multiply the random number by 100 before we round it down. the following would give us a random number between 0 and 99: math.floor(math.random()*100); hence us wanting to add 1, to give us a random number between 1 and 100: math.floor(math.random()*100) + 1; try updating both lines like this, then save and refresh — the game should now play like we are intending it to! other common errors there are other common errors you'll co...
....floor(math.random()*100); hence us wanting to add 1, to give us a random number between 1 and 100: math.floor(math.random()*100) + 1; try updating both lines like this, then save and refresh — the game should now play like we are intending it to! other common errors there are other common errors you'll come across in your code. this section highlights most of them. syntaxerror: missing ; before statement this error generally means that you have missed a semicolon at the end of one of your lines of code, but it can sometimes be more cryptic. for example, if we change this line inside the checkguess() function: var userguess = number(guessfield.value); to var userguess === number(guessfield.value); it throws this error because it thinks you are trying to do something different. you s...
...=== number(guessfield.value); it throws this error because it thinks you are trying to do something different. you should make sure that you don't mix up the assignment operator (=) — which sets a variable to be equal to a value — with the strict equality operator (===), which tests whether one value is equal to another, and returns a true/false result. note: see our syntaxerror: missing ; before statement reference page for more details about this error. the program always says you've won, regardless of the guess you enter this could be another symptom of mixing up the assignment and strict equality operators. for example, if we were to change this line inside checkguess(): if (userguess === randomnumber) { to if (userguess = randomnumber) { the test would always return true, caus...
Getting started with Ember - Learn web development
ded html structure, which eliminates small differences between implementations, allowing for easier comparison. later on in the tutorial, we'll focus on adding code to our application to fix some of todomvc's biggest faults. installing the ember tooling ember uses a command-line interface (cli) tool for building and scaffolding parts of your application. you'll need node and npm installed before you can install ember-cli. go here to find out how to install node and npm, if you haven't already got them. now type the following into your terminal to install ember-cli: npm install -g ember-cli this tool provides the ember program in your terminal, which is used to create, build, develop, test, and scaffold your application (run ember --help for a full list of commands and their o...
...reate, build, develop, test, and scaffold your application (run ember --help for a full list of commands and their options). to create a brand new application, type the following in your terminal. this creates a new directory inside the current directory you are in called todomvc, containing the scaffolding for a new ember app. make sure you navigate to somewhere appropriate in the terminal before you run it. (good suggestions are your "desktop" or "documents" directories, so that it is easy to find): ember new todomvc or, on windows: npx ember-cli new todomvc this generates a production-ready application development environment that includes the following features by default: development server with live reload. plugin-architecture that allows for third-party packages t...
... babel and webpack integration. automated testing environment that runs your tests in the browser, allowing you to test like a user. transpilation, and minification, of both css and javascript for production builds. conventions for minimizing the differences between applications (allowing easier mental context switching). getting ready to build our ember project you'll need a code editor before continuing to interact with your brand new project. if you don't have one configured already, the ember atlas has some guides on how to set up various editors. installing the shared assets for todomvc projects installing shared assets, as we're about to do, isn't normally a required step for new projects, but it allows us to use existing shared css so we don't need to try to guess at what css i...
...r shared css files, so that they become part of our build without having to explicitly @import them into the app.css file (this would require url rewrites at build time and therefore be less efficient and more complicated to set up). in ember-cli-build.js, find the following code: let app = new emberapp(defaults, { // add options here }); add the following lines underneath it before saving the file: app.import('node_modules/todomvc-common/base.css'); app.import('node_modules/todomvc-app-css/index.css'); for more information on what ember-cli-build.js does, and for other ways in which you can customize your build / pipeline, the ember guides have a page on addons and dependencies. finally, find app.css, located at app/styles/app.css, and paste in the following...
React interactivity: Editing, filtering, conditional rendering - Learn web development
e={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. a ui for editing in order to allow users to edit a task, we have to provide a user interface for them to do so. first, import usestate into the todo component like we did before with the app component, by updating the first import statement to this: import react, { usestate } from "react"; we'll now use this to set an isediting state, the default state of which should be false. add the following line just inside the top of your todo(props) { … } component definition: const [isediting, setediting] = usestate(false); next, we're going to rethink the <todo /> componen...
...condition to change what is rendered by the browser. to write a condition in jsx, we can use a ternary operator. in the case of our <todo /> component, our condition is "is this task being edited?" change the return statement inside todo() so that it reads like so: return <li classname="todo">{isediting ? editingtemplate : viewtemplate}</li>; your browser should render all your tasks just like before. to see the editing template, you will have to change the default isediting state from false to true in your code for now; we will look at making the edit button toggle this in the next section! toggling the <todo /> templates at long last, we are ready to make our final core feature interactive. to start with, we want to call setediting() with a value of true when a user presses the "edit" but...
...nter; once they submit the form, we need to use a callback prop to update our state with the new name of the task. we'll start by making a new hook for storing and setting the new name. still in todo.js, put the following underneath the existing hook: const [newname, setnewname] = usestate(''); next, create a handlechange() function that will set the new name; put this underneath the hooks but before the templates: function handlechange(e) { setnewname(e.target.value); } now we'll update our editingtemplate's <input /> field, setting a value attribute of newname, and binding our handlechange() function to its onchange event. update it as follows: <input id={props.id} classname="todo-text" type="text" value={newname} onchange={handlechange} /> finally, we need to create a funct...
...ttribute values change accordingly. however, our buttons still don't actually filter the todos in the ui! let's finish this off. filtering tasks in the ui right now, our tasklist constant in app() maps over the tasks state and returns a new <todo /> component for all of them. this is not what we want! a task should only render if it is included in the results of applying the selected filter. before we map over the tasks state, we should filter it (with array.prototype.filter()) to eliminate objects we don't want to render. update your tasklist like so: const tasklist = tasks .filter(filter_map[filter]) .map(task => ( <todo id={task.id} name={task.name} completed={task.completed} key={task.id} toggletaskcompleted={toggletaskcompleted} deletetask=...
Beginning our React todo list - Learn web development
prerequisites: familiarity with the core html, css, and javascript languages, knowledge of the terminal/command line. objective: to introduce our todo list case study, and get the basic app structure and styling in place. our app's user stories in software development, a user story is an actionable goal from the perspective of the user. defining user stories before we begin our work will help us focus our work. our app should fulfill the following stories: as a user, i 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 on...
...defaultchecked will be "true" — a string literal. remember — this is actually javascript, not html! the aria-pressed attribute used in our earlier code snippet has a value of true because aria-pressed is not a true boolean attribute in the way checked is. ...
...rem 0.8rem; border: 2px solid #565656; } .todo-text:focus { box-shadow: inset 0 0 0 2px; } /* checkbox styles */ .c-cb { box-sizing: border-box; font-family: arial, sans-serif; -webkit-font-smoothing: antialiased; font-weight: 400; font-size: 1.6rem; line-height: 1.25; display: block; position: relative; min-height: 44px; padding-left: 40px; clear: left; } .c-cb > label::before, .c-cb > input[type="checkbox"] { box-sizing: border-box; top: -2px; left: -2px; width: 44px; height: 44px; } .c-cb > input[type="checkbox"] { -webkit-font-smoothing: antialiased; cursor: pointer; position: absolute; z-index: 1; margin: 0; opacity: 0; } .c-cb > label { font-size: inherit; font-family: inherit; line-height: inherit; display: inline-block; margin-bot...
...px; height: 44px; } .c-cb > input[type="checkbox"] { -webkit-font-smoothing: antialiased; cursor: pointer; position: absolute; z-index: 1; margin: 0; opacity: 0; } .c-cb > label { font-size: inherit; font-family: inherit; line-height: inherit; display: inline-block; margin-bottom: 0; padding: 8px 15px 5px; cursor: pointer; touch-action: manipulation; } .c-cb > label::before { content: ""; position: absolute; border: 2px solid currentcolor; background: transparent; } .c-cb > input[type="checkbox"]:focus + label::before { border-width: 4px; outline: 3px dashed #228bec; } .c-cb > label::after { box-sizing: content-box; content: ""; position: absolute; top: 11px; left: 9px; width: 18px; height: 7px; transform: rotate(-45deg); border: solid;...
Starting our Svelte Todo list app - Learn web development
ill issue the following warning: (!) plugin svelte: a11y: <img> element should have an alt attribute src/components/todos.svelte 1: <h1>svelte to-do list</h1> 2: 3: <img height="32" width="88" src="https://udn.realityripple.com/samples/b0/98dase3c7d.png"> ^ created public/build/bundle.js in 220ms [2020-07-15 04:07:43] waiting for changes... moreover, our editor can display this warning even before calling the compiler: you can tell svelte to ignore this warning for the next block of markup with a comment beginning with svelte-ignore, like this: <!-- svelte-ignore a11y-missing-attribute --> <img height="32" width="88" src="https://udn.realityripple.com/samples/b0/98dase3c7d.png"> note: with vscode you can automatically add this ignore comment by clicking on the quick fix... link or p...
.... svelte aims to implement all of them in its compiler, and most of them have already been ported to svelte. on github you can see which accessibility checks are still missing. you can check the meaning of each rule by clicking on its link. styling our markup let's make the todo list look a little better. ...
...rem 0.8rem; border: 2px solid #565656; } .todo-text:focus { box-shadow: inset 0 0 0 2px; } /* checkbox styles */ .c-cb { box-sizing: border-box; font-family: arial, sans-serif; -webkit-font-smoothing: antialiased; font-weight: 400; font-size: 1.6rem; line-height: 1.25; display: block; position: relative; min-height: 44px; padding-left: 40px; clear: left; } .c-cb > label::before, .c-cb > input[type="checkbox"] { box-sizing: border-box; top: -2px; left: -2px; width: 44px; height: 44px; } .c-cb > input[type="checkbox"] { -webkit-font-smoothing: antialiased; cursor: pointer; position: absolute; z-index: 1; margin: 0; opacity: 0; } .c-cb > label { font-size: inherit; font-family: inherit; line-height: inherit; display: inline-block; margin-bot...
...px; height: 44px; } .c-cb > input[type="checkbox"] { -webkit-font-smoothing: antialiased; cursor: pointer; position: absolute; z-index: 1; margin: 0; opacity: 0; } .c-cb > label { font-size: inherit; font-family: inherit; line-height: inherit; display: inline-block; margin-bottom: 0; padding: 8px 15px 5px; cursor: pointer; touch-action: manipulation; } .c-cb > label::before { content: ""; position: absolute; border: 2px solid currentcolor; background: transparent; } .c-cb > input[type="checkbox"]:focus + label::before { border-width: 4px; outline: 3px dashed #228bec; } .c-cb > label::after { box-sizing: content-box; content: ""; position: absolute; top: 11px; left: 9px; width: 18px; height: 7px; transform: rotate(-45deg); border: solid;...
Advanced Svelte: Reactivity, lifecycle, accessibility - Learn web development
pens to the nameel variable. to start with, add the following line at the beginning of the newtodo.svelte <script> section: import { onmount } from 'svelte' and these lines at the end of it: console.log('initializing:', nameel) onmount( () => { console.log('mounted:', nameel) }) now remove the if (autofocus) nameel.focus() line to avoid throwing the error we were seeing before. the app will now work again, and you'll see the following in your console: initializing: undefined mounted: <input id="todo-0" class="input input__lg" type="text" autocomplete="off"> as you can see, while the component is initializing nameel is undefined, which makes sense because the node input doesn't even exist yet. after the component has been mounted, svelte assigned a reference...
...uld also call the removeeventlistener() function when the node is destroyed. note: all this is just standard webapi functionality; nothing here is specific to svelte. we could achieve all this in our todo component whenever we add or remove the <input> from the dom, but we would have to be very careful to add the event listener after the node has been added to the dom, and remove the listener before the node is removed from the dom. in addition, our solution would not be very reusable. that's where svelte actions come into play. basically they let us run a function whenever an element has been added to the dom, and after removal from the dom. in our immediate use case, we will define a function called selectonfocus() that will receive a node as parameter. the function will add an event lis...
...from inside todo.svelte; add the following import statement just below the others: import { selectonfocus } from '../actions.js' and remove the selectonfocus() definition from todo.svelte — we no longer need it there. reusing our action to demonstrate our action's reusability, let's make use of it in newtodo.svelte. import selectonfocus() from actions.js in this file too, as before: import { selectonfocus } from '../actions.js' add the use:selectonfocus directive to the <input>, like this: <input bind:value={name} bind:this={nameel} use:selectonfocus type="text" id="todo-0" autocomplete="off" class="input input__lg" /> with a few lines of code we can add functionality to regular html elements, in a very reusable and declarative way. it just takes an import...
...instead: const focusoninit = (node) => node && typeof node.focus === 'function' && node.focus() and then in our markup we just need to add another use: directive: <input bind:value={name} use:selectonfocus use:focusoninit ... our onedit() function can now be much simpler: function onedit() { editing = true // enter editing mode } as a last example before we move on, let's go back to our todo.svelte component and give focus to the edit button after the user presses save or cancel. we could try just reusing our focusoninit action again, adding use:focusoninit to the edit button. but we'd be introducing a subtle bug. when you add a new todo, the focus will be put on the edit button of the recently added todo. that's because the focusoninit action i...
Focus management with Vue refs - Learn web development
ned". this seems weird. your button ref was defined when you activated the "edit" button, but now it’s not. what is going on? well, remember that when we change isediting to true, we no longer render the section of the component featuring the "edit" button. this means there's no element to bind the ref to, so it becomes undefined. you might now be thinking "hey, don’t we set isediting=false before we try to access the ref, so therefore shouldn't the v-if now be displaying the button?” this is where the virtual dom comes into play. because vue is trying to optimize and batch changes, it won't immediately update the dom when we set isediting to false. so when we call focusonedit(), the "edit" button has not been rendered yet. instead, we need to wait until after vue undergoes the next dom...
... is in a different component to our "edit" button, we can't just set focus inside the "edit" button’s click event handler. instead, we can use the fact that we remove and re-mount our todoitemeditform component whenever the "edit" button is clicked to handle this. so how does this work? well, vue components undergo a series of events, known as a lifecycle. this lifecycle spans from all the way before elements are created and added to the vdom (mounted), until they are removed from the vdom (destroyed). vue lets you run methods at various stages of this lifecycle using lifecycle methods. this can be useful for things like data fetching, where you may need to get your data before your component renders, or after a property changes. the list of lifecycle methods are below, in the order that the...
...re created and added to the vdom (mounted), until they are removed from the vdom (destroyed). vue lets you run methods at various stages of this lifecycle using lifecycle methods. this can be useful for things like data fetching, where you may need to get your data before your component renders, or after a property changes. the list of lifecycle methods are below, in the order that they fire. beforecreate() — runs before the instance of your component is created. data and events are not yet available. created() — runs after your component is initialized but before the component is added to the vdom. this is often where data fetching occurs. beforemount() — runs after your template is compiled, but before your component is rendered to the actual dom. mounted() — runs after your com...
...nt 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 dom. mounted() — runs after your component is mounted to the dom. can access refs here. beforeupdate() — runs whenever data in your component changes, but before the changes are rendered to the dom. updated() — runs whenever data in your component has changed and after the changes are rendered to the dom. beforedestroy() — runs before a component is removed from the dom. destroyed() — runs after a component has been removed from the dom activated() — only used in components w...
Styling Vue components with CSS - Learn web development
avascript objects that manage the app's data and an html-based template syntax that maps to the underlying dom structure. for installation, and to use some of the more advanced features of vue (like single file components or render functions), you'll need a terminal with node + npm installed. objective: to learn about styling vue components. styling vue components with css before we move on to add more advanced features to our app, we should add some basic css to make it look better. vue has three common approaches to styling apps: external css files. global styles in single file components (.vue files). component-scoped styles in single file components. to help familiarize you with each one, we'll use a combination of all three to give our app a nicer look and fee...
...e 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. ...
...n and (min-width: 620px) { body { font-size: 1.9rem; line-height: 1.31579; } } /*end resets*/ next, in your src/main.js file, import the reset.css file like so: import './assets/reset.css'; this will cause the file to get picked up during the build step and automatically added to our site. the reset styles should be applied to the app now. the images below show the look of the app before and after the reset is applied. before: after: noticeable changes include the removal of the list bullets, background color changes, and changes to the base button and input styles. adding global styles to single file components now that we've reset our css to be uniform across browsers, we need to customize the styles a bit more. there are some styles that we want to apply across componen...
...ed; cursor: pointer; position: absolute; z-index: 1; top: -2px; left: -2px; width: 44px; height: 44px; margin: 0; opacity: 0; } .custom-checkbox > .checkbox-label { font-size: inherit; font-family: inherit; line-height: inherit; display: inline-block; margin-bottom: 0; padding: 8px 15px 5px; cursor: pointer; touch-action: manipulation; } .custom-checkbox > label::before { content: ""; box-sizing: border-box; position: absolute; top: 0; left: 0; width: 40px; height: 40px; border: 2px solid currentcolor; background: transparent; } .custom-checkbox > input[type="checkbox"]:focus + label::before { border-width: 4px; outline: 3px dashed #228bec; } .custom-checkbox > label::after { box-sizing: content-box; content: ""; position: absolute; ...
Handling common accessibility problems - Learn web development
ncrementally. non-native complicated form controls are problematic because they tend to involve a lot of nested <div>s, and the browser does not know what to do with them by default. if you are inventing them yourself, you need to make sure that they are keyboard accessible; if you are using some kind of third-party framework, carefully review the options available to see how accessible they are before diving in. bootstrap looks to be fairly good for accessibility, for example, although making bootstrap a little more accessible by rhiana heath explores some of its issues (mainly related to color contrast), and looks at some solutions. regularly updated dynamic content can be a problem because screenreader users might miss it, especially if it updates unexpectedly. if you have a single-page app...
...t screenreader usage and what works best for screenreaders. also see screen reader user survey #6 results for some interesting screenreader usage statistics. voiceover voiceover (vo) comes free with your mac/iphone/ipad, so it's useful for testing on desktop/mobile if you use apple products. we'll be testing it on mac os x on a macbook pro. to turn it on, press cmd + f5. if you've not used vo before, you will be given a welcome screen where you can choose to start vo or not, and run through a rather useful tutorial to learn how to use it. to turn it off again, press cmd + f5 again. note: you should go through the tutorial at least once — it is a really useful way to learn vo. when vo is on, the display will look mostly the same, but you'll see a black box at the bottom left of the scre...
... regularly gives you reminders of what commands to use in certain places. have a play with vo now; you can then go on to play with some of our examples in the screenreader testing section. nvda nvda is windows-only, and you'll need to install it. download it from nvaccess.org. you can choose whether to make a donation or download it for free; you'll also need to give them your e-mail address before you can download it. once downloaded, install it — you double click the installer, accept the license and follow the prompts. to start nvda, double click on the program file/shortcut, or use the keyboard shortcut ctrl + alt + n. you'll see the nvda welcome dialog when you start it. here you can choose from a couple of options, then press the ok button to get going. nvda will now be active o...
...r" — this is a key that you need to press in addition to the actual nvda keyboard shortcuts to get them to work. using a modifier like this is common with screenreaders, to enable them to keep their commands from clashing with other commands. in the case of nvda, the modifier can either be insert (the default), or capslock (can be chosen by checking the first checkbox in the nvda welcome dialog before pressing ok). note: nvda is more subtle than voiceover in terms of how it highlights where it is and what it is doing. when you are scrolling through headings, lists, etc., items you are selected on will generally be highlighted with a subtle outline, but this is not always the case for all things. if you get completely lost, you can press ctrl + f5 to refresh the current page and begin from th...
Introduction to automated testing - Learn web development
ons. once loaded, you can perform live, interactive cross-browser testing with a website. if you notice an issue with the ui, then you can share it with your colleagues by capturing a screenshot of your vm with the screenshot button. you can also record a video of your test session by hitting the recorder button in your test session. with the in-built image editor, highlight your screenshot before you push it to your colleagues. using the mark as bug button you can push bugs to numerous third-party tools such as jira, asana, trello, and more. that way you can log a bug directly from your test session on lambdatest to your project management instance. check out all the third-party lambdatest integrations. note: all the videos and images captured inside a test session are captured i...
... then pass the test results back to sauce labs. it has several clients available to allow you to make calls to the api using your favourite environment, be it php, java, node.js, etc. let's have a brief look at how we'd access the api using node.js and node-saucelabs. first, set up a new npm project to test this out, as detailed in setting up node and npm. use a different directory name than before, like sauce-test for example. install the node sauce labs wrapper using the following command: npm install saucelabs create a new file inside your project root called call_sauce.js. give it the following contents: const saucelabs = require('saucelabs'); let myaccount = new saucelabs({ username: "your-sauce-username", password: "your-sauce-api-key" }); myaccount.getaccountdetails(fun...
...ally retrieve details of your account plan, sessions, builds, etc. it has several clients available to allow you to make calls to the api using your favourite environment, be it php, java, node.js, etc. let's have a brief look at how we'd access the api using node.js. first, set up a new npm project to test this out, as detailed in setting up node and npm. use a different directory name than before, like bstack-test for example. create a new file inside your project root called call_bstack.js. give it the following contents: const request = require("request"); let bsuser = "browserstack_username"; let bskey = "browserstack_access_key"; let baseurl = "https://" + bsuser + ":" + bskey + "@www.browserstack.com/automate/"; function getplandetails(){ request({uri: baseurl + "plan.json"}...
...recordable by manual testing alone. testingbot has several api clients you can use to interact with the api, including clients for nodejs, python, ruby, java and php. below is an example on how to interact with the testingbot api with the nodejs client testingbot-api. first, set up a new npm project to test this out, as detailed in setting up node and npm. use a different directory name than before, like tb-test for example. install the node testingbot wrapper using the following command: npm install testingbot-api create a new file inside your project root called tb.js. give it the following contents: const testingbot = require('testingbot-api'); let tb = new testingbot({ api_key: "your-tb-key", api_secret: "your-tb-secret" }); tb.gettests(function (err, tests) { console.lo...
Implementing feature detection - Learn web development
rentposition(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 standard for feature detection tests, and we'll look at that later on. before we move on, we'd like to say one thing upfront — don't confuse feature detection with browser sniffing (detecting what specific browser is accessing the site) — this is a terrible practice that should be discouraged at all costs. see using bad browser sniffing code for more details. writing your own feature detection tests in this section, we'll look at implementing your own feature detecti...
... look at the different effects these two files have 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). give it the following contents: const conditional = document.queryselector('.conditional'); const testelem = document.createelement('div'); if (testelem.style.flex !== undefined && testelem.style.flexflow !== undefined) { conditional.setattribute('href', 'flex-layout.css'); } else { conditional.setattribute('href', 'float-layout.css'); } here we are grabbing a...
... as modernizr-css.html and modernizr-css.css. update your <link> element in your html so it points to the correct css file (you should also update your <title> element to something more suitable!): <link href="modernizr-css.css" rel="stylesheet"> above this <link> element, add a <script> element to apply the modernizr library to the page, as shown below. this needs to be applied to the page before any css (or javascript) that might make use of it. <script src="modernizr-custom.js"></script> now edit your opening <html> tag, so that it looks like this: <html class="no-js"> at this point, try loading your page, and you'll get an idea of how modernizr works for css features. if you look at the dom inspector of your browser's developer tools, you'll see that modernizr has updated yo...
...s attaching the google maps api to the page. next, fill in the your-api-key placeholder text in the second <script> element (as it is now) with a valid google maps api key. to get a key, sign in to a google account, go to the get a key/authentication page, then click the blue get a key button and follow the instructions. ...
Introduction to cross browser testing - Learn web development
ssible of being able to use your content. this is one of the great challenges of web development. note: we'll cover defensive coding later in the module too. why do cross browser issues occur? there are many different reasons why cross browser issues occur, and note that here we are talking about issues where things behave different across different browsers / devices / browsing preferences. before you even get to cross browser issues, you should have already fixed out bugs in your code (see debugging html, debugging css, and what went wrong? troubleshooting javascript from previous topics to refresh your memory if needed). cross browser issues commonly occur because: sometimes browsers have bugs, or implement features differently. this situation is a lot less bad than it used to be; ba...
...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 frozen (i.e. no more new work done on them) a long time before a new feature was even invented. as an example, if you want to use cutting edge javascript features in your site, they might not work in older browsers. if you need to support older browsers, you might have to not use those, or convert your code to old fashioned syntax using some kind of cross-compiler where needed. some devices may have constraints that cause a web site to run slowly, or displa...
...ble experience on ie 8 and 9, and be accessible with wcag aa compliance. now you know your target testing platforms, you should go back and review the required featureset and what technologies you are going to use. for example, if the e-commerce site owner wants a webgl-powered 3d tour of each product built into the product pages, they will need to accept that this just won't work in ie versions before 11. you'd have to agree to provide a version of the site without this feature to users of older ie versions. you should compile a list of the potential problem areas. note: you can find browser support information for technologies by looking up the different features on mdn — the site you're on! you should also consult caniuse.com, for some further useful details. once you've agreed on the...
...en isn't going to give the same visual experience as a 4" mobile screen, regardless of how you program your site. accept that your site just isn't going to work in some older browsers, and move on. this is ok, provided your client/userbase is ok with it. normally your development will involve a combination of the above three approaches. the most important thing is that you test each small part before committing it — don't leave all the testing till the end! testing/discovery after each implementation phase, you will need to test the new functionality. to start with, you should make sure there are no general issues with your code that are stopping your feature from working: test it in a couple of stable browsers on your system, like firefox, safari, chrome, or ie/edge. do some lo-fi ac...
Client-side tooling overview - Learn web development
a single project. equally, a single configuration file for a tool like webpack can be hundreds of lines long, most of which are magical incantations that seem to do the job but which only a master engineer will fully understand! from time to time, even the most experienced of web developers get stuck on a tooling problem; it is possible to waste hours attempting to get a tooling pipeline working before even touching a single line of application code. if you have found yourself struggling in the past, then don’t worry — you are not alone. in these articles, we won’t answer every question about web tooling, but we will provide you with a useful starting point of understanding the fundamentals, which you can then build from. as with any complex topic, it is good to start small, and graduall...
...a code formatter, which we’ll make use of later on in the module. bundlers/packagers these are tools that get your code ready for production, for example by “tree-shaking” to make sure only the parts of your code libraries that you are actually using are put into your final production code, or "minifying" to remove all the whitespace in your production code, making it as small as possible before it is uploaded to a server. parcel is a particularly clever tool that fits into this category — it can do the above tasks, but also helps to package assets like html, css, and image files into convenient bundles that you can then go on to deploy, and also adds dependencies for you automatically whenever you try to use them. it can even handle some code transformation duties for you. webpack i...
...ing frameworks, auditing tools, and more. this stage of the development process is one that you want the least amount of active interaction with so that once it is configured, it runs mostly automatically, only popping up to say hello if something has gone wrong. testing tools these generally take the form of a tool that will automatically run tests against your code to make sure it is correct before you go any further (for example, when you attempt to push changes to a github repo). this can including linting, but also more sophisticated procedures like unit tests, where you run part of your code, making sure they behave as they should. frameworks for writing tests include jest, mocha, and jasmine. automated test running and notification systems include travis ci, jenkins, circle ci, and...
... you aren’t already in the web community, it is hard to find out exactly which ones to go for! this is one reason we wrote this series of articles, to hopefully provide that first step that is hard to find otherwise. you’ll probably need a combination of the following things: experienced teachers, mentors, fellow students, or colleagues that have some experience, have solved such problems before, and can give advice. a useful specific place to search. general web searches for front-end developer tools are generally useless unless you already know the name of the tool you are searching for. if you are using the npm package manager to manage your dependencies for example, it is a good idea to go to the npm homepage and search for the type of tool you are looking for, for example try...
Creating Sandboxed HTTP Connections
ice (nsiobserverservice) is used to send general notifications, including the two cookie ones. the addobserver method is used to add an observer for a certain topic and takes in three agruments: an object than implements nsiobserver the topic to listen for. for cookies, the two topics are: http-on-modify-request - happens after the cookie data has been loaded into the request, but before the request is sent. http-on-examine-response - happens after the response is received, but before the cookies are processed whether to hold a weak reference to the observer argument. use false. in order to avoid memory leaks, the observer needs to be removed at one point. the removeobserver method takes in the listener object and the topic and removes it from the notification l...
... new value is appened, otherwise the 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. ...
... true, the new value is appened, otherwise the old value is overwritten. these methods provide all the required functionality needed to modify cookies before they are processed/sent, allowing for sandboxed cookie connections that don't affect the user's cookies. http referrer if the http request needs to have a referrer set, two additional steps are needed after the nsichannel is created, but before it is opened. first, a nsiuri needs to be generated for the referrer url. ...
...ds provide all the required functionality needed to modify cookies before they are processed/sent, allowing for sandboxed cookie connections that don't affect the user's cookies. http referrer if the http request needs to have a referrer set, two additional steps are needed after the nsichannel is created, but before it is opened. first, a nsiuri needs to be generated for the referrer url. ...
Old Thunderbird build
d that you only use options that you fully understand. for example, to create a debug build instead of a release build, that file would contain: ac_add_options --enable-debug for more on configuration options, see the page configuring build options. note that if you use an moz_objdir it cannot be a sibling folder to your source directory. use an absolute path to be sure! building thunderbird 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 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 ...
...tion listed under running below. building thunderbird and lightning if you've set up your build environment as above, then all you need to do is: echo 'ac_add_options --enable-calendar' >> mozconfig in the comm-central directory, or just add the ac_add_options --enable-calendar line to your mozconfig with your favorite editor. then just re-run the mach command above (you can do the addition before running mach 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 thunderbird executable will be found in your object directory (under comm-central/), which is prefixed with obj-. the exact name depends on your system and os. for example, a m...
...able in particular, and its dependencies, are located under the dist/bin folder under the object directory. to run the executable from your comm-central working directory: windows: obj-.../dist/bin/thunderbird.exe linux: obj-.../dist/bin/thunderbird os x: obj-.../dist/daily.app/contents/macos/thunderbird how to update and build again in your comm-central directory, run the same command as before: python client.py checkout then just re-run the mach command above. this will only recompile files that changed, but it's still a long haul. rebuilding to build after making changes, run ./mozilla/mach build again. this will only rebuild what is necessary for these changes. it is also possible to rebuild specifically. if you changed c or c++ files, run: ./mozilla/mach build binaries i...
...tual error is. check if your mozilla/ is a symlink. a symlink there is not supported. check for @topsrcdir@ or relative paths in your mozconfig. those have caused several problems historically and tend to be poorly tested when the build system changes. if on windows you get link errors like "lnk1102: out of memory" or "lnk1318: unexpected pdb error; ok (0)", try deleting the largest .pdb files before rushing out the door to buy more ram. clobbering (see below) will also remove those files. try with a clean obj-dir. you can clean out previous build artefacts using ./mozilla/mach clobber references general build documentation comm-central using the mozilla symbol server ...
Eclipse CDT Manual Setup
ring indexing, and so on.) it's recommended that you have a separate workspace containing only a single project for each mozilla source tree [rational], and that you choose a directory outside the mozilla source. something like $home/eclipse-workspaces/mozilla-tree-1, for example. after selecting an appropriate directory, click ok, then close the "welcome" tab when the main eclipse window opens. before you proceed any further, check that your changes to eclipse's memory limits have taken effect and are present in eclipse/help > about eclipse > installation details > configuration. to avoid confusion in this and the following sections, note that "workspace preferences" and "project properties" are different things (we'll get to the details below). whenever you create a new workspace for a mozi...
...tion details > configuration. to avoid confusion in this and the following sections, note that "workspace preferences" and "project properties" are different things (we'll get to the details below). whenever you create a new workspace for a mozilla source tree, you should be sure to turn off the following two settings in the workspace preferences (window > preferences, or eclipse > preferences) before creating a project in that workspace: in "general > workspace", disable "build automatically" in "c/c++ > indexer", disable "automatically update the index" turning off automatic indexing prevents the cpu intensive indexer from running at various stages during the steps below before we're ready. select "general > content types", expand "text > c source file > c++ source file", click "add" ...
...ing a list of all the files in the source tree). click on the little green button beside this message to open the "progress" tab, and keep an eye on the "refreshing workspace" item as you continue with the steps below. (if an "indexing" item starts after the "refreshing the workspace" item has finished, click the little red box beside that item to cancel it, since we want to configure the project before the indexer runs.) initial project properties so that the indexer will run faster and give better results, and so that eclipse doesn't give results for irrelevant files, you should add some resource filters to have eclipse ignore certain non-source files and directories. note, you must not make eclipse ignore your (main) object directory. that object directory is needed to resolve include paths...
...ot selected. highlight (select) "cdt gcc build output parser", then in the "language settings provider options" that appear below, make sure that "share setting entries between projects (global provider)" is not ticked. if the main object directory for your source tree is a fennec build: in the "cdt gcc build output parser", change the compiler command pattern to (.*gcc)|(.*[gc]\+\+)|(clang) (before this change it should have been "(gcc)|([gc]\+\+)|(clang)"). this pattern is what cdt uses to identify compiler commands when parsing the build output. by default, it recognizes commands of the form "gcc", "g++", "c++", and "clang". this is fine for a desktop build, where the commands are in fact "gcc" and "g++". for fennec builds, however, most of the commands are something like "arm-linux-andro...
Experimental features in Firefox
version of the firefox browser, firefox nightly, every day. these nightly builds of firefox typically include experimental or partially-implemented features, including those for proposed or cutting-edge web platform standards. this page lists features that are in nightly versions of firefox along with information on how to activate them, if necessary. you can test your web sites and applications before these features get released and ensure everything will still work with the latest web technology capabilities. to test these experimental features, you need to download firefox nightly or firefox developer edition. which you need is described alongside each feature's description below. editor's note: when adding features to these tables, please try to include a link to the relevant bug or bugs...
... the user's device or computer. the specification is still a work-in-progress. see bug 1602129 for our progress on this api. release channel version added enabled by default? nightly 73 no developer edition 73 no beta 73 no release 73 no preference name dom.webgpu.enabled html dom api global event: beforeinput the global beforeinput event is sent to an <input> element—or any element whose contenteditable attribute is enabled—immediately before the element's value changes. release channel version added enabled by default? nightly 74 no developer edition 74 no beta 74 no release 74 no preference name dom...
...see bug 934425 for more details. ...
... version added enabled by default? nightly 77 yes developer edition 77 no beta 77 no release 77 no preference name network.ftp.enabled developer tools mozilla's developer tools are constantly evolving. we experiment with new ideas, add new features, and test them on the nightly and developer edition channels before letting them go through to beta and release. the features below are the current crop of experimental developer tool features. color scheme simulation adds an option to simulate different color schemes allowing to test @prefers-color-scheme media queries. using this media query lets your style sheet specify whether it prefers a light or dark user interface. this feature lets you test your code w...
DeferredTask.jsm
to use it, you first need to import the code module into your javascript scope: components.utils.import("resource://gre/modules/deferredtask.jsm"); use this, for instance, if you write data to a file and you expect that you may have to rewrite data very soon afterwards. ...
...lves when the new execution terminates. if the task is not running and the timer is not armed, the method returns a resolved promise. promise finalize(); example firefox 28 note this section describes about deferredtask.jsm in firefox 28.0 or higher. set up a function or an asynchronous task whose execution can be triggered after a defined delay. multiple attempts to run the task before the delay has passed are coalesced. the task cannot be re-entered while running, but can be executed again after a previous run finished. a common use case occurs when a data structure should be saved into a file every time the data changes, using asynchronous calls, and multiple changes to the data may happen within a short time: let savedeferredtask = new deferredtask(function* () { yield o...
...n be disarmed to reset the delay, or just to cancel execution: savedeferredtask.disarm(); savedeferredtask.arm(); // the task will be executed in 2 seconds from now. when the internal timer fires and the execution of the task starts, the task cannot be canceled anymore. it is, however, possible to arm the timer again during the execution of the task, in which case the task will need to finish before the timer is started again, thus guaranteeing a time of inactivity between executions that is at least equal to the provided delay. the "finalize" method can be used to ensure that the task terminates properly. the promise it returns is resolved only after the last execution of the task is finished. to guarantee that the task is executed for the last time, the method prevents any attempt to arm ...
...at this point, then one last execution from start to finish will happen again, immediately after the current execution terminates. if the timer is not armed, the "finalize" method only ensures that any running task terminates. ...
Localization sign-off reviews
qa measure for maintaining a localization from release-to-release. only evaluates new l10n work. this is done by generating a diff between the new release revision being considered and the previously approved release revision. focuses on technical accuracy and completion of l10n work, not translation quality. evaluates new release revisions, not entire l10n repos. does not need to be approved before revision merge between release channels, although it is recommended. sign-off review criteria since the scope of each qa review process varies, the criteria used to evaluate a localizer's work also varies. in principle, they share basic elements, but sign-off reviews are only for evaluating the changes between your latest approved revision and the new revision you've submitted for release approv...
...ng your localization's files. newly translated strings that shouldn't have been translated self-explanatory enough, right? access key changes we ensure that when access keys are changed that they are consistent with the keyboard layout for that particular locale and not blended between two or more distinct layouts. how it all works a large part of the review process takes place before you even submit your request for a sign-off review. to put it simply, when we receive your request, we expect that you have spent 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 ...
...it your request for a sign-off review. to put it simply, when we receive your request, we expect that you have spent time testing your work and making sure all strings have been localized and that your changes are relatively functional. your review request symbolically represents that you have worked on your localization, tested it successfully, and found it to represent the best of your work. so before you request your sign-off review, be sure that it is as ready as it can be. there is a specific process to follow in bugzilla for requesting these reviews: file a bug requesting the review. attach your files to the bug. once attached, open the attachment details. in the attachment details, select the ? from the dropdown menu next to the appropriate approval flags (see image). this will displa...
...ecific bugzilla bugs. as your work is approved, you'll see a green circle in the farthest column to the right. if bugs are discovered, your technical review/sign-off is rejected and the bugs are filed in bugzilla. once filed, they appear on your dashboard for you to fix. once they are fixed, push your fix to your repo, attach it to the corresponding bug using the same mercurial revision number as before, and then request another review. the process is then repeated until the bug is fixed to satisfaction. the diff generated for sign-off reviews the image to the right illustrates the revisions diff between the current release revision and your newly proposed release revision. this is generated from the revision attachment in your bugzilla bug and evaluated to verify the technical accuracy of your...
Localization technical reviews
gs in the file toolkit/chrome/global/intl.properties. for more info about utf-7 in firefox, see bug 441876. ...
...to put it simply, when we receive your request, we expect that you have spent time testing your work and making sure all strings have been localized and that your language pack is relatively functional. ...
...r request for a technical review. to put it simply, when we receive your request, we expect that you have spent time testing your work and making sure all strings have been localized and that your language pack is 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 technical review, be sure that it is as ready as it can be. there is a specific process to follow in bugzilla for requesting these reviews: file a bug requesting the review. attach your files to the bug. once attached, open the attachment details. in the attachment details, select the ? from the dropdown menu next to the review flag. this will display a text box to assign t...
...ays: within the bug and through your team's dashboard. if your work is approved, you'll see a + review flag next to your attached revision in your request bug. if bugs are discovered, your technical review is rejected (- review flag) and the bugs are filed in bugzilla. once they are fixed, push your fix to your repo, attach it to the corresponding bug using the same mercurial revision number as before, and then request another review. the process is then repeated until the bug is fixed to satisfaction. these bugs are also pulled into the dashboards, which track your revision's progress. in order to ultimately have your revision included as an official build, your dashboards must be at 100% green. to the right, you'll see the current dashboard page for a german localization. revisions are appr...
DMD
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/linux64/common-opt or a similar file before pushing. launch use mach run --dmd; use --mode to choose the mode. add --debug to run under gdb. trigger there are three ways to trigger a dmd snapshot. visit about:memory and click the dmd 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 e...
... or more seconds and may make firefox freeze temporarily. if you see the "opened" line, it tells you where the file was saved. it's always in a temp directory, and the filenames are always of the form dmd-<pid>. desktop firefox (mac) build build with these options: ac_add_options --enable-dmd if building via try server, modify browser/config/mozconfigs/macosx64/common-opt or a similar file before pushing. launch use mach run --dmd; use --mode to choose the mode. add --debug to run under lldb. trigger follow the trigger instructions for linux. note that on mac this step can take 30+ seconds. desktop firefox (windows) build build with these options: ac_add_options --enable-dmd if building via try server, modify browser/config/mozconfigs/win32/common-opt. also, add this line to bui...
...md prep in order to prepare your device for running fennec with dmd enabled, you will need to do a few things. first, you will need to push the libdmd.so library to the device so that it can by dynamically loaded by fennec. you can do this by running: adb push $objdir/dist/bin/libdmd.so /sdcard/ second, you will need to make an executable wrapper for fennec which sets an environment variable before launching it. (if you are familiar with the recommended "--es env0" method for setting environment variables when launching fennec, note that you cannot use this method here because those are processed too late in the startup process. if you are not familiar with that method, you can ignore this parenthetical note.) first make the executable wrapper on your host machine using the editor of your c...
... from other source, adjust the app identifier as necessary. adb shell su # you need root access for the setprop command to take effect setprop wrap.org.mozilla.fennec_$username "/data/local/tmp/dmd_fennec" once this is set up, starting the org.mozilla.fennec_$username app will use the wrapper script. launch launch fennec either by tapping on the icon as usual, or from the command line (as before, be sure to replace org.mozilla.fennec_$username with the app identifier as appropriate). adb shell am start -n org.mozilla.fennec_$username/.app trigger use the existing memory-report dumping hook: adb shell am broadcast -a org.mozilla.gecko.memory_dump in logcat, you should see output similar to this: i/dmd (20731): opened /storage/emulated/0/download/memory-reports/dmd-default-2073...
pkfnc.html
returns the function returns one of these values: if successful, a pointer to a certificate structure. if unsuccessful, null. description a nickname is an alias for a certificate subject. there may be multiple certificates with the same subject, and hence the same nickname. this function will return the newest certificate that matches the subject, based on the notbefore / notafter fields of the certificate. when you are finished with the certificate structure returned by pk11_findcertfromnickname, you must free it by calling cert_destroycertificate. the pk11_findcertfromnickname function calls the password callback function set with pk11_setpasswordfunc and passes it the pointer specified by the wincx parameter. pk11_findkeybyanycert finds the private key ...
...owing 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 before freeing the slot. do not try to free the string yourself. pk11_gettokenname gets the name of the token. syntax #include <pk11func.h> char *pk11_gettokenname(pk11slotinfo *slot); parameters this function has the following parameter: slot a pointer to a slot info structure. returns the function returns one of these valu...
...ing 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 token (a string). if unsuccessful, null. description if the slot is freed, the string with the token name may also be freed. if you want to preserve it, copy the string before freeing the slot. do not try to free the string yourself. pk11_ishw finds out whether a slot is implemented in hardware or software. syntax #include <pk11func.h> #include <prtypes.h> prbool pk11_ishw(pk11slotinfo *slot); parameters this function has the following parameter: slot a pointer to a slot info structure. retur...
...etry argument is pr_true, indicating that the password was tried and is wrong, the callback function should return null to indicate that it is unsuccessful, rather than attempting to return the same password again. failing to terminate when the retry argument is pr_true can result in an endless loop. several functions in the nss libraries use the password callback function to obtain the password before performing operations that involve the protected information. the third parameter to the password callback function is application-defined and can be used for any purpose. for example, communicator uses the parameter to pass information about which window is associated with the modal dialog box requesting the password from the user. when nss libraries call the password callback function, the valu...
sslintro.html
ed in this document, the ssl reference. other apis that may be exposed in the header files are not supported for application use. initialization initialization includes setting up configuration files, setting global defaults, and setting up callback functions. functions used in the initialization part of an application can include the following: pr_init. initializes nspr. must be called before any other nss functions. pk11_setpasswordfunc. sets the global callback function to obtain passwords for pkcs #11 modules. required. nss_init. sets up configuration files and performs other tasks required to run network security services. nss_init is not idempotent, so call it only once. required. ssl_optionsetdefault. changes default values for all subsequently opened sockets as long as...
...called once for each default value that needs to be changed. optional. nss_setdomesticpolicy, nss_setexportpolicy, nss_setfrancepolicy, or ssl_cipherpolicyset. these functions tell the library which cipher suites are permitted by policy (for example, to comply with export restrictions). cipher suites disabled by policy cannot be enabled by user preference. one of these functions must be called before any cryptographic operations can be performed with nss. ssl_cipherprefsetdefault. enables all ciphers chosen by user preference. optional. initializing caches ssl peers frequently reconnect after a relatively short time has passed. to avoid the overhead of repeating the full ssl handshake in situations like this, the ssl protocol supports the use of a session cache, which retains informat...
...r_enumeratehostent pr_connect pr_getconnectstatus when an application imports a socket into ssl after the tcp connection on that socket has already been established, it must call ssl_resethandshake to determine whether ssl should behave like an ssl client or an ssl server. note that this step would not be necessary if the socket weren't already connected. for an ssl socket that is configured before it is connected, ssl figures this out when the application calls pr_connect or pr_accept. if the socket is already connected before ssl gets involved, you must provide this extra hint. functions that can be used by both clients and servers during communication include the following: pr_send or pr_write pr_read or pr_recv pr_geterror pr_getpeername pr_sleep pr_malloc pr_free pr_po...
...r example, http) determines which end has responsibility to talk first. the end that has to talk first should call pr_send or pr_write, and the other end should call pr_read or pr_recv. use ssl_forcehandshake when the socket has been prepared for a handshake but neither end has anything to say immediately. this occurs, for example, when an https server has received a request and determines that before it can answer the request, it needs to request an authentication certificate from the client. at the http protocol level, nothing more is being said (that is, no http request or response is being sent), so the server first uses ssl_rehandshake to begin a new handshake and then call ssl_forcehandshake to drive the handshake to completion. functions used by callbacks an ssl application typical...
Hacking Tips
hared.h, it is composed of the return address, a descriptor (a small value), the jsfunction (if it is even) or a jsscript (if the it is odd, remove it to dereference the pointer) and the frame ends with the number of actual arguments (a small value too). if you want to know at which lir the code is failing at, the js::ion::codegenerator::generatebody function can be intrumented to dump the lir id before each instruction. for (; iter != current->end(); iter++) { ionspew(ionspew_codegen, "instruction %s", iter->opname()); […] masm.store16(imm32(iter->id()), address(stackpointer, -8)); // added if (!iter->accept(this)) return false; […] } this modification will add an instruction which abuse the stack pointer to store an immediate value (the lir id) to a location...
...1 passes. /* open your png viewer with the result of iongraph */ this gdb instrumentation is supposed to work with debug builds, or with optimized build compiled with --enable-jitspew configure flag. external programs such as iongraph, dot, and your png viewer are search into the path, otherwise custom one can either be configured with environment variables (gdb_iongraph, gdb_dot, gdb_pngviewer) before starting gdb, or with gdb parameters (set iongraph-bin <path>, set dot-bin <path>, set pngviewer-bin <path>) within gdb. enabling gdb instrumentation may require launching a js shell executable that shares a directory with a file name "js-gdb.py". if js/src/js does not provide the "iongraph" command, try js/src/shell/js. gdb may complain that ~/.gdbinit requires modification to authorize user s...
...d you want to build a 32-bits browser, it might be hard to find the relevant 32-bits dependencies. you can use padenot's scripts which will magically setup a chrooted 32-bits environment and do all the things (c) for you (you just need to modify the mozconfig file). using rr on a test get the command line for your test run using -s: ./jit_test.py -s $js_shell saved-stacks/async.js insert 'rr' before the shell invocation: rr $js_shell -f $js_src/jit-test/lib/prolog.js --js-cache $js_src/jit-test/.js-cache -e "const platform='linux2'; const libdir='$js_src/jit-test/lib/'; const scriptdir='$js_src/jit-test/tests/saved-stacks/'" -f $js_src/jit-test/tests/saved-stacks/async.js (note that the above is an example; simply setting js_shell and js_src will not work). or if this is an intermittent, r...
...o measure with the datenow() function call which returns the number of milliseconds, with a decimal part for sub-milliseconds. js> datenow() - datenow() -0.0009765625 benchmarking with sub-milliseconds (browser) in a simillar way as datenow() in the js shell, you can use performance.now() in the javascript code of a page. dumping the javascript heap from the shell, you can call the dumpheap before firefox function to dump out all gc things (reachable and unreachable) that are present in the heap. by default the function writes to stdout, but a filename can be specified as an argument. example output might look as follows: 0x1234abcd b global object ========== # zone 0x56789123 # compartment http://gmail.com [in zone 0x56789123] # compartment http://gmail.com/iframe [in zone 0x56789123] ...
Garbage collection
e to do a bit of marking work, then let the mutator (javascript program) run a bit, then do another bit of marking work. thus, instead of one long pause for marking, the gc does a series of short pauses. the pauses can be set to be 10ms or less. there is always a possibility that a long pause will be required. if the allocation rate is high during incremental gc, the engine may run out of memory before finishing the incremental gc. if so, the engine must immediately restart a full, non-incremental gc in order to reclaim some memory and continue execution. incremental write barrier the problem that requires a write barrier incremental gc requires a write barrier for correctness. todo decent diagrams the basic problem is as follows (see dictionary for color terms). say object a is black and ...
... 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 through a and we are all done with a, because a is black. thus, b is live but will be collected. the write barrier is a piece of code that runs just before a pointer store occurs and records just enough information to make sure that live objects don't get collected. the spidermonkey incremental write barrier spidermonkey uses a (relatively!) simple, common incremental write barrier called a snapshot-at-the-beginning allocate-black barrier. to understand how this barrier works, first assume that we're going to do an incremental gc during which no ...
...hen we encounter them during gc graph traversal. instead, we append them to a list. after marking everything live we scan through the list to null out references to garbage. but this also means that pre-barriers are inadequate to prevent incremental gc from missing edges due to graph mutation. live cells will be marked either because they're reachable or because they were marked by a pre-barrier before being removed from the graph. but reachable weak references aren't traced! so you could read one out and write it behind the frontier and no pre-barriered removal will mark it (it's not being removed, just read). so we barrier the read instead; if you ever read a weak reference in the middle of an ongoing incremental gc, then the target of the weak ref will be marked. implementation details wri...
...dled specially. the private field itself is opaque to the engine, but it may point to things that need to be marked, e.g., an array of jsobject pointers. in this example, if the private field is overwritten, the jsobject pointers could be 'lost', so a write barrier must be invoked to mark them. js::nativeobject::privatewritebarrierpre takes care of this by invoking the jsobject's class trace hook before the private field is set. another detail is that write barriers can be skipped when initializing fields of newly allocated objects, because no pointer is being overwritten. sweeping todo generational gc todo gc statistics api you can access the light statistics the gc keeps at runtime through the gc statistics api. source files gc/gc.{h,cpp} defines gc internal api functions, including ...
Secure Development Guidelines
\0 terminated! buffer bounds validations (bbv) thou shalt check the array bounds of all strings (indeed, all arrays), for surely where thou typest "foo" someone someday shall type "supercalifragilisticexpialidocious". ...
...o_something(); delete ptr1; do_something_else(); ptr2 = new char[-1] // oom } catch (...) { delete ptr1; delete ptr2; } new will throw an exception — ptr1 is already freed in the try block then freed again in the catch block freeing un-initialized data free data in the catch block assumption is that it’s initialized in the try block if the try block throws before the variable is initialized, the catch block will operate on un-intialized data freeing un-initialized data example: int main(){ char *ptr; try { ptr = new char[-1]; // oom } catch(...) { delete ptr; } } freeing un-initialized data: prevention be careful when freeing data in catch blocks make sure the try block can’t throw before data is initia...
...) { delete ptr; } } freeing un-initialized data: prevention be careful when freeing data in catch blocks make sure the try block can’t throw before data is initialized initialize variables when they’re declared; for example, set pointers to null memory leaks usually occur when memory is allocated in a try block after the allocation, something throws in the try block before memory is freed in the try block the catch block does not foresee this and doesn't free the memory freeing un-initialized data example: int main(){ char *p; try { p = new char [1000]; ... code that might throw an exception ... delete p; } catch (...) { ... } } memory leaks: prevention any acquired resource in a try block should ...
...does not foresee this and doesn't free the memory freeing un-initialized data example: int main(){ char *p; try { p = new char [1000]; ... code that might throw an exception ... delete p; } catch (...) { ... } } memory leaks: prevention any acquired resource in a try block should be freed in a catch block (if the try block throws before the resource is freed) might be helpful to initialize variables null for pointers -1 for file descriptors ...
Avoiding leaks in JavaScript XPCOM components
nguages, functions have access to the variables that are in scope where they are created. a closure is a code × environment pair: function objects are not just the code; they're also the environment. since all the variables in that environment are reachable from the function object, the objects referenced by those variables are reachable from the function. to understand closures a little better before examining how they can cause leaks, consider the following example, in which there are two pairs of function objects, and each pair has an instance of the private_data variable: // this function returns an array containing two functions. function function_array() { // once this function is done running, this variable is still // accessible to the functions created here. var private_d...
...the iterator object is an xpcom object that is wrapped so the javascript code can use it. the _filterradiogroup object is a javascript function that is wrapped so that xpcom code can use it. the reason closures matter here is that the _filterradiogroup function has access to the iterator variable. ...
...however, a better fix is to move the filter function outside of the function, since the power of closures is not necessary in this case (and there's also no need to create a new function object for the filter each time this code is executed). this same problem can also happen if the function is inside of an object. ...
...ce(components.interfaces.nsiobserverservice); service.addobserver(observer, "open-new-tab-request", false); in this example, there is a similar cycle between observe and service. (but since service is a global variable, just fixing the cycle doesn't fix the leak.) don't store short-lived objects as javascript properties of short-lived dom nodes i mentioned earlier that, in versions of mozilla before 1.8, setting arbitrary javascript properties on elements (or using xbl fields) causes that element's javascript wrapper to be rooted until the document stops being displayed. this can be a problem if there are large objects reachable from that wrapper that should go away before the document stops being displayed. the worst example of this problem is tabbrowser. tabbrowser is an xbl binding that ...
mozIStorageStatement
the given sql statement. void initialize( in mozistorageconnection adbconnection, in autf8string asqlstatement ); parameters adbconnection a mozistorageconnection database connection. asqlstatement string key representing the sql statement. finalize() finalizes a statement which releases all resources that were allocated for it. you must call this method on every active statement before you try to call mozistorageconnection.close(). void finalize(); note: this method does not need to be used from native callers because you have to release the statement in order to not leak. finalize will be called for you when the reference count on the statement goes to zero. clone() creates a copy of the statement whose state will be mozistoragestatement.moz_storage_statement_ready. mozi...
...g with the of the column name for the specified index. getcolumnindex() obtains the index of the column with the specified name. unsigned long getcolumnindex( in autf8string aname ); parameters aname name of the column. return value the zero-based numerical index for the column to get data from. reset() resets the bound parameters and statement execution state. this must be called before reusing the statement. note: javascript callers should always wrap their execution in a try block, and have a reset statement in a finally block. see the overview document on storage for more details. void reset() escapestringforlike() escapes a string for sql like search. note: consumers will have to use same escape char when doing statements such as: ...like '?1' escape '/'.... see the s...
...tion functions these functions are discussed in more detail with sample code in the overview document. executeasync() starts the execution of a query asynchronously using the currently bound parameters. the optional callback routine receives notifications about the progress of the query. for sample code and more details, see the overview document. note: the statement does not have to be reset before being reused. mozistoragependingstatement executeasync( [optional] mozistoragestatementcallback acallback ); parameters acallback a callback object that will be notified of progress, errors, and query completion. this parameter is optional. return value a mozistoragependingstatement object that can be used to cancel the execution of the statement. executestep() executes a query with...
...d of progress, errors, and query completion. this parameter is optional. return value a mozistoragependingstatement object that can be used to cancel the execution of the statement. executestep() executes a query with the currently bound parameters, and steps through the results one row at a time. for sample code and more details, see the overview document. note: the statement must be reset before being reused. boolean executestep(); return value returns a boolean indicating whether there are more rows or not. row data may be accessed using mozistoragevaluearray methods on the statement. step() identical to calling executestep(), and then calling reset() when no more rows are returned. note: this method may only be called from javascript code. boolean step() return value true if ...
nsIDOMEvent
ventdefault() has been called for this event. read only. eventphase unsigned short used to indicate which phase of event flow is currently being evaluated. read only. explicitoriginaltarget nsidomeventtarget the explicit original target of the event. if the event was retargeted for some reason other than an anonymous boundary crossing, this will be set to the target before the retargeting occurs. for example, mouse events are retargeted to their parent node when they happen over text nodes (bug 185889), and in that case .target will show the parent and .explicitoriginaltarget will show the text node. .explicitoriginaltarget differs from .originaltarget in that it will never contain anonymous content. read only. istrusted boolean read only. ...
... parent node when they happen over text nodes (bug 185889), and in that case .target will show the parent and .explicitoriginaltarget will show the text node. .explicitoriginaltarget differs from .originaltarget in that it will never contain anonymous content. read only. istrusted boolean read only. originaltarget nsidomeventtarget the original target of the event, before any retargetings. read only. target nsidomeventtarget used to indicate the eventtarget to which the event was originally dispatched. read only. timestamp domtimestamp used to specify the time (in milliseconds relative to the epoch) at which the event was created. due to the fact that some systems may not provide this information the value of timestamp may be not ava...
...alnsevent(); parameters none. return value getpreventdefault() note: use the defaultprevented attribute instead. this method will be removed in future releases, see bug 691151. boolean getpreventdefault(); parameters none. return value initevent() this method is used to initialize the value of an event created through the documentevent interface. this method may only be called before the event has been dispatched via the dispatchevent method, though it may be called multiple times during that phase if necessary. if called multiple times the final invocation takes precedence. if called from a subclass of event interface only the values specified in the initevent method are modified, all other attributes are left unchanged. void initevent( in domstring eventtypearg, in boo...
...ed and, unlike stoppropagation() its effect is immediate. void stopimmediatepropagation(); parameters none. stoppropagation() the stoppropagation method is used prevent further propagation of an event during event flow. if this method is called by any eventlistener the event will cease propagating through the tree. the event will complete dispatch to all listeners on the current eventtarget before event flow stops. this method may be used during any stage of event flow. void stoppropagation(); parameters none. ...
nsIDocShell
sidocumentcharsetinfo interface were merged into nsidocshell in gecko 12.0. eldestpresshell nsipresshell presentation shell for the oldest document, if this docshell is currently transitioning between documents. read only. native code only! forcedcharset nsiatom a character set to override the page's default character set while processing; this is tried before using any other character set during page loads. note: prior to gecko 12.0, this attribute was part of a separate nsidoccharsetinfo interface. hasfocus boolean tells the docshell that it now has focus or has lost focus. obsolete since gecko 1.9.2 historyid unsigned long long the id of the docshell in the session history. read only. isact...
...p tab docshell in some cases, such as when handling link clicks. docshells are not app tabs unless told otherwise. isexecutingonloadhandler boolean returns true if the docshell is currently executing the onload handler. read only. isinunload boolean find out whether the docshell is currently in the middle of a page transition (after the onunload event has fired, but before the new document has been set up) read only. isoffscreenbrowser boolean if true, this docshell is not visible in the traditional sense, but is being actively rendered to the screen (such as by being painted to a canvas), and should be treated accordingly. layouthistorystate nsilayouthistorystate loadedtransindex long keeps track of the previous sht...
...of the apptype attribute used by thunderbird and seamonkey to indicate that email messages or web pages are composed in this window. busy_flags_none 0 returned by the busyflags attribute when the nsidocshell is not loading a document. busy_flags_busy 1 returned by the busyflags attribute when the nsidocshell is loading a document from the network. busy_flags_before_page_load 2 returned by the busyflags attribute when the nsidocshell has started loading a document from the network, but no data has been received yet. busy_flags_page_loading 4 returned by the busyflags attribute when the nsidocshell is receiving data from the network. load_cmd_normal 0x1 returned by the loadtype attribute for normal loads. load_cmd_...
... defined in nsiwebnavigation. note that using flags outside load_flags_mask is only allowed if passing in a non-null loadinfo. and even some of those might not be allowed. use at your own risk. firstparty true if this is the master top-level document. preparefornewcontentmodel() reset state to a new content model within the current document and the document viewer. called by the document before initiating an out of band document.write(). void preparefornewcontentmodel(); parameters none. resumerefreshuris() restart the xpcom timers for each meta-refresh uri in this docshell, and this docshell's children, recursively. if the timers are already running, this has no effect. void resumerefreshuris(); parameters none. native code only!setchildoffset set the offset of this child in its con...
nsINavBookmarkObserver
toolkit/components/places/nsinavbookmarksservice.idlscriptable this interface is an observer for bookmark changes. ...
...ted(in long long aitemid, in long long avisitid, in prtime atime, in unsigned long atransitiontype, in nsiuri auri, in long long aparentid, in acstring aguid, in acstring aparentguid); void onseparatoradded(in print64 parent, in print32 index); obsolete since gecko 1.9 void onseparatorremoved(in print64 parent, in print32 index); obsolete since gecko 1.9 methods onbeforeitemremoved() obsolete since gecko 21.0 (firefox 21.0 / thunderbird 21.0 / seamonkey 2.18) note: this method was removed in gecko 21.0 as part of bug 826409. this method notifies this observer that an item is about to be removed. it is called before the actual removal takes place. void onbeforeitemremoved( in long long aitemid, in unsigned short aitemtype, in long long ap...
... item the item which was replaced. newitem the new item which replaced item. onitemvisited() this method notifies that the item was visited. can be invoked only for type_bookmark items. normally in bookmarks we use the last visit date, and normally the time will be a new visit that will be more recent, but this is not guaranteed. you should check to see if it is actually more recent before using this new time. see onitemchanged() method property = "cleartime" for when all visit dates are deleted for the uri. note: the reported time is the time of the visit that was added, which may be well in the past since the visit time can be specified. this means that the visit the observer is told about may not be the most recent visit for that page. void onitemvisited( in long long aitemid,...
...s parent. index the separator's index inside its parent. onseparatorremoved() obsolete since gecko 1.9 (firefox 3) notify this observer that a separator has been removed. void onseparatorremoved( in print64 parent, in print32 index ); parameters parent the id of the separator's parent. index the separator's old index in its parent. using onbeforeitemremoved() in gecko 1.9.1 if you wish to support onbeforeitemremoved() in applications based on gecko 1.9.1, you must implement your observer's queryinterface() method to match on both nsinavbookmarkobserver and nsinavbookmarkobserver_mozilla_1_9_1_additions, as shown below. queryinterface: function(iid) { if (iid.equals(ci.nsinavbookmarkobserver) || iid.equals(ci.nsinavbookmarkobserver...
nsINavHistoryObserver
on the global history. 1.0 66 introduced gecko 1.8 inherits from: nsisupports last changed in gecko 21.0 (firefox 21.0 / thunderbird 21.0 / seamonkey 2.18) warning: if you are in the middle of a batch transaction, there may be a database transaction active. you can still access the database in this situation but be careful (of what?). ...
...ed(in nsiuri auri, in astring apagetitle); void onvisit(in nsiuri auri, in long long avisitid, in prtime atime, in long long asessionid, in long long areferringid, in unsigned long atransitiontype, in acstring aguid, out unsigned long aadded); constants constant value description attribute_favicon 3 the page's favicon changed. methods onbeforedeleteuri() obsolete since gecko 21.0 (firefox 21.0 / thunderbird 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 ope...
... to have ever existed for this function to be called. delete notifications aren't quite 100% accurate. batch delete operations take place in two steps; the notifications come first, followed by a bulk delete. if an error occurs in between these two steps (for example, an out of memory error), then you may get a notification even though the page doesn't wind up getting deleted. note: see using onbeforedeleteuri() in gecko 1.9.1 for how to implement this in gecko 1.9.1 void onbeforedeleteuri( in nsiuri auri, in acstring aguid ); parameters auri the uri of the page about to be deleted. aguid the unique id associated with the page. onbeginupdatebatch() notifies you that a batch of things are about to change. you should avoid doing any heavy-duty processing until onendupdate...
...about to be removed; this is one of the nsinavbookmarksservice.constants defined in the nsinavbookmarksservice interface. aguid the unique id associated with the page. aadded incremented by query nodes when the visited uri belongs to them. if no such query exists, the history result creates a new query node dynamically. it is used in places views only and can be ignored. using onbeforedeleteuri() in gecko 1.9.1 if you wish to support onbeforedeleteuri() in applications based on gecko 1.9.1, you must implement your observer's queryinterface() method to match on both nsinavhistoryobserver and nsinavhistoryobserver_mozilla_1_9_1_additions, as shown below. queryinterface: function(iid) { if (iid.equals(ci.nsinavhistoryobserver) || iid.equals(ci.nsinavhistoryobserver_mozilla...
nsITransactionListener
nsitransactionmanager calls the nsitransaction.undo() method of a transaction. void didundo( in nsitransactionmanager amanager, in nsitransaction atransaction, in nsresult aundoresult ); parameters amanager the nsitransactionmanager undoing the transaction. atransaction the transaction being undone. aundoresult the nsresult returned after undoing the transaction. willbeginbatch() called before a nsitransactionmanager begins a batch. boolean willbeginbatch( in nsitransactionmanager amanager ); parameters amanager the nsitransactionmanager beginning a batch. return value willdo() called before a nsitransactionmanager calls a transaction's nsitransaction.dotransaction() method. boolean willdo( in nsitransactionmanager amanager, in nsitransaction atransaction ); parameters aman...
...nsactionmanager beginning a batch. return value willdo() called before a nsitransactionmanager calls a transaction's nsitransaction.dotransaction() method. boolean willdo( in nsitransactionmanager amanager, in nsitransaction atransaction ); parameters amanager the nsitransactionmanager doing the transaction. atransaction the transaction being executed. return value willendbatch() called before a nsitransactionmanager ends a batch. boolean willendbatch( in nsitransactionmanager amanager ); parameters amanager the nsitransactionmanager ending a batch. return value willmerge() called before a nsitransactionmanager tries to merge a transaction, that was just executed, with the transaction at the top of the undo stack. boolean willmerge( in nsitransactionmanager amanager, in nsitr...
...ecuted, with the transaction at the top of the undo stack. boolean willmerge( in nsitransactionmanager amanager, in nsitransaction atoptransaction, in nsitransaction atransactiontomerge ); parameters amanager the nsitransactionmanager ending a batch. atoptransaction the transaction at the top of the undo stack. atransactiontomerge the transaction to merge. ...
...boolean willundo( in nsitransactionmanager amanager, in nsitransaction atransaction ); parameters amanager the nsitransactionmanager undoing the transaction. atransaction the transaction being undone. ...
nsIXULTemplateQueryProcessor
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 retrieved using the result's nsixultemplateresult.getbindingfor() and nsixultemplateresult.getbindingobjectfor() methods. the template builder must call initializeforbuilding() before the other methods, except for translateref(). the builder will then call compilequery() for each query in the template to compile the queries. when results need to be generated, the builder will call generateresults(). the initializeforbuilding(), compilequery() and addbinding() methods may not be called after generateresults() has been called until the builder indicates that the generated output...
... the sort hints are the flags in nsixulsortservice. return value -1 if aleft < aright 0 if aleft == aright 1 if aleft > aright compilequery() compile a query from a node. the result of this function will later be passed to generateresults() for result generation. if null is returned, the query will be ignored. the template builder will call this method once for each query within the template, before any results can be generated using generateresults(), but after initializeforbuilding() has been called. this method should not be called again for the same query unless the template is rebuilt. the reference variable may be used by the query processor as a placeholder for the reference point, or starting point in the query. the member variable is determined from the member attribute on the templ...
...atasources the list of nsiuri objects and/or nsidomnode objects. arootnode the root node the builder is attached to. aistrusted true if the template is in a trusted document. abuilder the template builder. ashoulddelaybuilding whether the builder should wait to build the content or not. return value a datasource object. initializeforbuilding() initialize for query generation. this will be called before the rules are processed and whenever the template is rebuilt. this method must be called once before any of the other query processor methods except for translateref(). void initializeforbuilding( in nsisupports adatasource, in nsixultemplatebuilder abuilder, in nsidomnode arootnode ); parameters adatasource datasource for the data. abuilder the template builder. arootnode the root node t...
...tring into a result. this is used as the reference point by the template builder when generating the first level of content. for recursive generation, the result from the parent generation phase will be used directly as the reference so a translation is not needed. this allows all levels to be generated using objects that all implement the nsixultemplateresult interface. this method may be called before initializeforbuilding(), so the implementation may use the supplied datasource if it is needed to translate the reference. nsixultemplateresult translateref( in nsisupports adatasource, in astring arefstring ); parameters adatasource datasource for the data. arefstring the ref attribute string. return value the translated ref. see also a tutorial on how to implement a custom xul query pro...
Setting HTTP request headers
rfc6648 notifications the question that may be coming to your mind right now is, how do you get the nsihttpchannel when an http request is made. in the case your code initiates the request, you probably already have one. trapping other requests is done with notifications, which are a lot like events or signals found in other languages and frameworks. in particular, to get the nsihttpchannel just before the http request is made we need to observe the "http-on-modify-request" topic. (and yes, "http-on-modify-request" is a string.) note: there are many topics, besides just "http-on-modify-request", that you can get notifications about, for example "http-on-examine-response" and "xpcom-shutdown". you can also make up your own topics and send out your own notifications. for more information about...
...will be the nsihttpchannel. however, it is passed to us as an nsisupports. so we need to change the nsisupports into a nsihttpchannel which is what the queryinterface call does. and yes, converting objects from one kind to another is very ugly, and lacks (what is usually called) syntactic sugar. the second line of code in the if block should already be familiar to you. it is the same code we used before, earlier in this article, to add the http request header. the name of this object -- httprequestobserver -- isn't important. we could have named it anything we liked. registering after we've created the observer, we need to register it. in our case, we want to register it for the "http-on-modify-request" topic. we can do this with the code below. var observerservice = cc["@mozilla.org/observer-se...
...vice.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 httprequestobserver to be notified (by calling its observe method) when a "http-on-modify-request" topic takes place (which we know happens just before each http request). unregistering you should unregister the observer on shutdown. failing to do that may cause memory leaks. to unregister the observer use nsiobserverservice.removeobserver as follows: observerservice.removeobserver(httprequestobserver, "http-on-modify-request"); all-in-one example here is a slightly different version of our httprequestobserver object. while the previous version ...
... request). unregistering you should unregister the observer on shutdown. failing to do that may cause memory leaks. to unregister the observer use nsiobserverservice.removeobserver as follows: observerservice.removeobserver(httprequestobserver, "http-on-modify-request"); all-in-one example here is a slightly different version of our httprequestobserver object. while the previous version we showed before was good for learning, in an actual real-world application, you'd probably want to code it more like the following. var httprequestobserver = { observe: function(subject, topic, data) { if (topic == "http-on-modify-request") { var httpchannel = subject.queryinterface(ci.nsihttpchannel); httpchannel.setrequestheader("x-hello", "world", false); } }, get observerservice(...
Getting Started Guide
if you're already familiar with nscomptrs, then you might want to skip ahead to the reference manual or the faq. don't worry; the getting started guide is short. introduction what is nscomptr? nscomptr is a tool to help prevent leaks. nscomptr is a "smart pointer". it is a template class that acts, syntactically, just like an ordinary pointer in c or c++, i.e., you can apply * or -> to it to "get to" what it points at. nscomptr is smart in that, unlike a raw c++ pointer to an xpcom object, nscomptr manages addref, release, and queryinterface for you. ...
...y implement many interfaces. each interface is (at least conceptually) separately `reference counted'. that is, the interface keeps a count of the number of clients holding references to it. when that count goes to zero, the interface may delete itself. clients are expected to keep this reference count accurate by incrementing it when they acquire a reference to the interface, and decrementing it before they let go. to facilitate this, all interfaces inherit from an abstract base class that provides the member functions addref, and release. a rule of xpcom is that any function that creates or returns an interface pointer will have already addrefed it. the caller can then hold onto the reference indefinitely, calling release when it no longer needs it. when the last pointer to an interface is re...
... nscomptr<nsifoo> myfoo = ...; f( address_of(myfoo) ); void f( nscomptr<t>& ) do pass an nscomptr by reference for `in/out' parameters this is the prefered scheme for providing `in/out' parameters. ...
...'t know what ownership relationship the caller had to the input value, and hence, couldn't know whether to release it or not before assigning in the new value. by declaring the parameter as an nscomptr&, the relationship is explicit. summary an nscomptr is an owning reference. whatever it points to has been addrefed, counting the nscomptr as one of its `owners'. an nscomptr always calls release before letting go, whether the nscomptr is letting go so that it can point to a different object, or because the nscomptr is going out of scope. any time a new value is assigned into an nscomptr, the nscomptr automatically always releases its old referent, if any, and (unless you tell it you already have) addrefs the new. you use an nscomptr exactly as you would a raw xpcom interface pointer in almost ...
Plug-in Development Overview - Plugins
", string 4: "aiff audio", and string 5: "jpeg image format." str#' 126: string 1 can contain a descriptive message about the plug-in. this message, which is in html format, is displayed by the browser in its "about plug-ins" page. string 2 can contain the name of the plug-in, thus allowing the name the user sees to be different from the name of the file on disk. ...
... the browser calls these plug-in methods: npp_getvalue: query the plug-in for information. npp_print: request a platform-specific print operation for the instance. npp_setvalue: set the browser information. ...
...set the window or other target in which it draws, arrange for redrawing, and handle events. a windowless plug-in can call the following netscape methods to draw itself: npn_forceredraw: force a paint message for windowless plug-ins. npn_invalidaterect: invalidate an area in a windowless plug-in before repainting or refreshing. npn_invalidateregion: invalidate an area in a windowless plug-in before repainting or refreshing. the browser calls these plug-in methods: npp_getvalue: query the plug-in for information. npp_print: request a platform-specific print operation for the instance. npp_setvalue: set the browser information. npp_setwindow: set the window in which a plug-in draws. npp_handleevent: deliver a platform-specific event to the instance. the plug-in can call these netsc...
...nformation about these processes, see drawing and event handling. handling memory plug-in developers can take advantage of the memory features provided in the plug-in api to allocate and free memory. use the npn_memalloc method to allocate memory from the browser. use the npn_memfree method to free memory allocated with npn_memalloc. use the npn_memflush method to free memory (mac os only) before calling memory-intensive mac toolbox calls. sending and receiving streams streams are objects that represent urls and the data they contain. a stream is associated with a specific instance of a plug-in, but a plug-in can have more than one stream per instance. streams can be produced by the browser and consumed by a plug-in instance, or produced by an instance and consumed by the browser. each...
Streams - Plugins
er, pulled by the plug-in, or saved to a local file and passed to the plug-in. normal mode: the browser uses the npp_write method to "push" stream data to the instance incrementally as it is available. random-access mode: the plug-in calls the npn_requestread method to "pull" stream data. in general, this mode is more expensive, because the entire stream must be downloaded to a temporary file before use unless the stream comes from a local file or an http server that supports the byte-range extension to http. file mode: the browser saves the entire stream to a local file and passes the file path to the plug-in instance through the npp_streamasfile method. use this feature only as a last resort; plug-ins should implement an incremental stream-based interface wherever possible. streams sent...
...ak: the user canceled the stream directly by clicking the stop button or indirectly by some action, such as by deleting the instance or initiating higher-priority network operations. npres_network_err: the stream failed because of problems with the network, disk i/o error, lack of memory, or some other problem. finding out how much data the plug-in can accept after a call to npp_newstream and before writing data to the plug-in, the browser calls npp_writeready to determine the maximum number of bytes that the plug-in can consume. this function allows the browser to send only as much data to the instance as it can handle at one time, and it helps both the browser and the plug-in to use their resources efficiently. after a call to npp_newstream, in which the plug-in requested a normal-mode st...
...ows 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 before each call to npp_write. the value returned by npp_writeready indicates how many bytes the plug-in instance can accept for this stream. if the plug-in allocates memory for the entire stream at once, it can return a large number. this number tells the browser that it can pass as much data to the instance as possible in a single call to npp_write. the browser can write a smaller amount of data if d...
...: if you want to be sure that the npn_*stream functions are called in the order you want and behave the way you expect, combine npn_newstream, npn_write, and npn_destroy_stream in the same callback. sending the stream in random-access mode in random-access mode, the plug-in "pulls" stream data by calling the npn_requestread method. the browser must download the entire stream to a temporary file before it can be used, unless the stream comes from a local file or an http server that supports the byte-range extension to http. this mode consumes more resources than the others. random-access mode is determined in npp_newstream by setting the mode np_seek. this mode gives the plug-in instance random access to stream data as needed, through calls to npn_requestread. if the stream is not seekable, th...
AudioBufferSourceNode.AudioBufferSourceNode() - Web APIs
ithub.com/mdn/browser-compat-data and send us a pull request. ...
... ≤79firefox full support 53ie no support noopera full support 42safari ? ...
...i ? webview android full support 55notes full support 55notes notes before version 59, the default values were not supported.chrome android full support 55notes full support 55notes notes before version 59, the default values were not supported.firefox android full support 53opera android full support 42safari ios ? samsung internet android full support 6.0notes full support 6.0no...
...9, the default values were not supported.firefox android full support 53opera android full support 42safari ios ? ...
DelayNode() - Web APIs
ut https://github.com/mdn/browser-compat-data and send us a pull request. ...
... ≤79firefox full support 53ie no support noopera full support 42safari ? ...
...i ? webview android full support 55notes full support 55notes notes before version 59, the default values were not supported.chrome android full support 55notes full support 55notes notes before version 59, the default values were not supported.firefox android full support 53opera android full support 42safari ios ? samsung internet android full support 6.0notes full support 6.0no...
...9, the default values were not supported.firefox android full support 53opera android full support 42safari ios ? ...
DynamicsCompressorNode() - Web APIs
thub.com/mdn/browser-compat-data and send us a pull request. ...
... ≤79firefox full support 53ie no support noopera full support 42safari ? ...
...i ? webview android full support 55notes full support 55notes notes before version 59, the default values were not supported.chrome android full support 55notes full support 55notes notes before chrome 59, the default values were not supported.firefox android full support 53opera android full support 42safari ios ? samsung internet android full support 6.0notes full support 6.0not...
...9, the default values were not supported.firefox android full support 53opera android full support 42safari ios ? ...
Element.insertAdjacentHTML() - Web APIs
reparse the element it is being used on, and thus it does not corrupt the existing elements inside that element. this avoids the extra step of serialization, making it much faster than direct innerhtml manipulation. ...
...ement it is being used on, and thus it does not corrupt the existing elements inside that element. this avoids the extra step of serialization, making it much faster than direct innerhtml manipulation. ...
... elements inside that element. this avoids the extra step of serialization, making it much faster than direct innerhtml manipulation. syntax element.insertadjacenthtml(position, text); parameters position a domstring representing the position relative to the element; must be one of the following strings: 'beforebegin': before the element itself. 'afterbegin': just inside the element, before its first child. 'beforeend': just inside the element, after its last child. ...
...ition relative to the element; must be one of the following strings: 'beforebegin': before the element itself. 'afterbegin': just inside the element, before its first child. 'beforeend': just inside the element, after its last child. 'afterend': after the element itself. text the string to be parsed as html or xml and inserted into the tree. visualization of position names <!-- beforebegin --> <p> <!-- afterbegin --> foo <!-- beforeend --> </p> <!-- afterend --> note: the beforebegin and afterend positions work only if the node is in the dom tree and has a parent element. example // <div id="one">one</div> var d1 = document.getelementbyid('one'); d1.insertadjacenthtml('afterend', '<div id="two">two</div>'); // at this point, the new structure is: // <div id="one">on...
Element.insertAdjacentText() - Web APIs
the insertadjacenttext() method of the element interface inserts a given text node at a given position relative to the element it is invoked upon. syntax element.insertadjacenttext(position, element); parameters position a domstring representing the position relative to the element; must be one of the following strings: 'beforebegin': before the element itself. 'afterbegin': just inside the element, before its first child. 'beforeend': just inside the element, after its last child. 'afterend': after the element itself. element a domstring representing the text to be inserted into the tree. return value void. exceptions exception explanation syntaxerror the position specified is not a recognised value. visualization of position names...
...nt, before its first child. 'beforeend': just inside the element, after its last child. 'afterend': after the element itself. element a domstring representing the text to be inserted into the tree. return value void. exceptions exception explanation syntaxerror the position specified is not a recognised value. visualization of position names <!-- beforebegin --> <p> <!-- afterbegin --> foo <!-- beforeend --> </p> <!-- afterend --> note: the beforebegin and afterend positions work only if the node is in a tree and has an element parent. ...
...return value void. exceptions exception explanation syntaxerror the position specified is not a recognised value. visualization of position names <!-- beforebegin --> <p> <!-- afterbegin --> foo <!-- beforeend --> </p> <!-- afterend --> note: the beforebegin and afterend positions work only if the node is in a tree and has an element parent. example beforebtn.addeventlistener('click', function() { para.insertadjacenttext('afterbegin',textinput.value); }); afterbtn.addeventlistener('click', function() { para.insertadjacenttext('beforeend',textinput.value); }); have a look at our insertadjacenttext.html demo on github (see the source code too.) here we have a simple paragraph. you can enter some text into the form element, then press the insert...
...tn.addeventlistener('click', function() { para.insertadjacenttext('afterbegin',textinput.value); }); afterbtn.addeventlistener('click', function() { para.insertadjacenttext('beforeend',textinput.value); }); have a look at our insertadjacenttext.html demo on github (see the source code too.) here we have a simple paragraph. you can enter some text into the form element, then press the insert before and insert after buttons to insert it before or after the existing paragraph text using insertadjacenttext(). note that the existing text node is not added to — further text nodes are created containing the new additions. polyfill you can polyfill the insertadjacenttext() method in internet explorer 5.5 (maybe earlier) and higher with the following code: if (!element.prototype.insertadjacent...
GainNode() - Web APIs
Web › API › GainNode › GainNode
out https://github.com/mdn/browser-compat-data and send us a pull request. ...
... ≤79firefox full support 53ie no support noopera full support 42safari ? ...
...ri ? webview android full support 55notes full support 55notes notes before chrome 59, the default values were not supported.chrome android full support 55notes full support 55notes notes before chrome 59, the default values were not supported.firefox android full support 53opera android full support 42safari ios ? samsung internet android full support 6.0notes full support 6.0not...
...9, the default values were not supported.firefox android full support 53opera android full support 42safari ios ? ...
Ajax navigation example - Web APIs
rms 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 . ...
...\n</html>"; } ?> second_page.php: <?php $page_title = "second 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 . ...
....php</strong>. this content is stored into a php variable.</p>"; if (isset($_get["view_as"]) && $_get["view_as"] == "json") { echo json_encode(array("page" => $page_title, "content" => $page_content)); } else { ?> <!doctype html> <html> <head> <?php include "include/header.php"; echo "<title>" . $page_title . ...
...ader { position: fixed; display: table; top: 0; left: 0; width: 100%; height: 100%; } #ajax-loader > div { display: table-cell; width: 100%; height: 100%; vertical-align: middle; text-align: center; background-color: #000000; opacity: 0.65; } include/after_content.php: <p>this is the footer. ...
IIRFilterNode() - Web APIs
ttps://github.com/mdn/browser-compat-data and send us a pull request. ...
... ≤79firefox full support 53ie no support noopera full support 42safari ? ...
...i ? webview android full support 55notes full support 55notes notes before version 59, the default values were not supported.chrome android full support 55notes full support 55notes notes before version 59, the default values were not supported.firefox android full support 53opera android full support 42safari ios ? samsung internet android full support 6.0notes full support 6.0no...
...9, the default values were not supported.firefox android full support 53opera android full support 42safari ios ? ...
NotificationEvent - Web APIs
opera full support 37safari ? webview android no support nochrome android full support 42firefox android full support ...
... opera full support 37safari ? webview android no support nochrome android full support 42firefox android full support ...
... opera no support nosafari ? webview android no support nochrome android full support 48firefox android full support ...
... opera full support 37safari ? webview android no support nochrome android full support 42firefox android full support ...
OfflineAudioCompletionEvent.OfflineAudioCompletionEvent() - Web APIs
com/mdn/browser-compat-data and send us a pull request. ...
... ≤79firefox full support 53ie no support noopera full support 42safari ? ...
...i ? webview android full support 57notes full support 57notes notes before version 59, the default values were not supported.chrome android full support 57notes full support 57notes notes before chrome 59, the default values were not supported.firefox android full support 53opera android full support 42safari ios ? samsung internet android full support 6.0notes full support 6.0not...
...9, the default values were not supported.firefox android full support 53opera android full support 42safari ios ? ...
PerformanceEventTiming - Web APIs
the performanceeventtiming interface of the event timing api provides timing information for the event types listed below. auxclick beforeinput click compositionend compositionstart compositionupdate contextmenu dblclick dragend dragenter dragleave dragover dragstart drop input keydown keypress keyup mousedown mouseenter mouseleave mouseout mouseover mouseup pointerover pointerenter pointerdown pointerup pointercancel pointerout pointerleave gotpointercapture lostpointercapture touchstart touchend touchcancel properties performanceeventtiming.processingstart returns the time at which event dispatch started. performanceeventtiming.processingend returns the time at which the event dispatch ended. performanceeventtiming.cancelable returns th...
...ot removed. methods performanceeventtiming.tojson() converts the performanceeventtiming object to json. examples the following example shows how to use the api for all events: const observer = new performanceobserver(function(list) { const perfentries = list.getentries().foreach(entry => { // full duration const inputduration = entry.duration; // input delay (before processing event) const inputdelay = entry.processingstart - entry.starttime; // synchronous event processing time (between start and end dispatch). const inputsyncprocessingtime = entry.processingend - entry.processingstart; }); }); // register observer for event. observer.observe({entrytypes: ["event"]}); we can also directly query the first input delay. // keep t...
...processingstart; }); }); // register observer for event. observer.observe({entrytypes: ["event"]}); we can also directly query the first input delay. // keep track of whether (and when) the page was first hidden, see: // https://github.com/w3c/page-visibility/issues/29 // note: ideally this check would be performed in the document <head> // to avoid cases where the visibility state changes before this code runs. let firsthiddentime = document.visibilitystate === 'hidden' ? 0 : infinity; document.addeventlistener('visibilitychange', (event) => { firsthiddentime = math.min(firsthiddentime, event.timestamp); }, {once: true}); // sends the passed data to an analytics endpoint. this code // uses `/analytics`; you can replace it with your own url. function sendtoanalytics(data) { const bod...
... // report the fid value to an analytics endpoint. sendtoanalytics({fid}); } } // create a performanceobserver that calls `onfirstinputentry` for each entry. const po = new performanceobserver((entrylist) => { entrylist.getentries().foreach(onfirstinputentry); }); // observe entries of type `first-input`, including buffered entries, // i.e. entries that occurred before calling `observe()` below. po.observe({ type: 'first-input', buffered: true, }); } catch (e) { // do nothing if the browser doesn't support this api. } specifications specification status comment unknownthe definition of '[[member]]' in that specification. unknown initial definition. ...
Range.compareNode() - Web APIs
Web › API › Range › compareNode
obsolete since gecko 1.9 (firefox 3)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. the range.comparenode() returns a constant indicating the position of the node. the possible values are: node_before (0) node starts before the range node_after (1) node ends after the range node_before_and_after (2) node starts before and ends after the range node_inside (3) node starts after and ends before the range, i.e. the node is completely selected by the range. warning: this method has been removed from gecko 1.9 (firefox 3) and will not exist in future versions of firefox, which was the only browser implementing it; you should switch to range.compareboundarypoints() as soon as poss...
...e versions of firefox, which was the only browser implementing it; you should switch to range.compareboundarypoints() as soon as possible. ...
... example range = document.createrange(); range.selectnode(document.getelementsbytagname("div").item(0)); returnvalue = range.
..., node) { var noderange = node.ownerdocument.createrange(); try { noderange.selectnode(node); } catch (e) { noderange.selectnodecontents(node); } var nodeisbefore = range.compareboundarypoints(range.start_to_start, noderange) == 1; var nodeisafter = range.compareboundarypoints(range.end_to_end, noderange) == -1; if (nodeisbefore && !nodeisafter) return 0; if (!nodeisbefore && nodeisafter) return 1; if (nodeisbefore && nodeisafter) return 2; return 3; } syntax returnvalue = range.comparenode( referencenode ); parameters referencenode the node to compare with the range. example range = document.createrange(); range.selectnode(document.getelementsbytagname("div").item(0)); returnvalue = range.comparenode(document.getelementsbytagname("p").item...
WaveShaperNode.WaveShaperNode() - Web APIs
tps://github.com/mdn/browser-compat-data and send us a pull request. ...
... ≤79firefox full support 53ie no support noopera full support 42safari ? ...
...ri ? webview android full support 55notes full support 55notes notes before chrome 59, the default values were not supported.chrome android full support 55notes full support 55notes notes before chrome 59, the default values were not supported.firefox android full support 53opera android full support 42safari ios ? samsung internet android full support 6.0notes full support 6.0not...
...9, the default values were not supported.firefox android full support 53opera android full support 42safari ios ? ...
Establishing a connection: The WebRTC perfect negotiation pattern - Web APIs
this way, we avoid the risk of offers colliding. automatic rollback in setremotedescription() a key component to perfect negotiation is the concept o...
...n it needs to throw away a received offer if it's currently waiting for a reply to an offer it's already sent. the code checks to see if the message is an offer, and if so, if the local signaling state isn't stable. if it's not stable, and the local peer is the polite one, we need to trigger rollback so we can replace the outgoing offer with the new incoming one. and these must both be completed before we can proceed with handling the received offer. since there isn't a single "roll back and use this offer instead", performing this change on the polite peer requires two steps, executed in the context of promise.all(), which is used to ensure that both statements execute completely before continuing to handle the received offer. the first statement triggers rollback and the second sets the remo...
...caldescription() to create and set an appropriate local description, then we send it to the remote peer over the signaling server. on receiving an ice candidate on the other hand, if the received message is an ice candidate—indicated by the json object containing a candidate member—we deliver it to the local ice layer by calling the rtcpeerconnection method addicecandidate(). errors are, as before, ignored if we have just discarded an offer. explicit restartice() method added the techniques previously used to trigger an ice restart while handling the eventnegotiationneeded have significant flaws. these flaws have made it difficult to safely and reliably trigger a restart during negotiation. the perfect negotiation improvements have fixed this by adding a new restartice() method to rtcpee...
...ag to the next ice message sent. problem solved! rollback no longer supported in the pranswer state the last of the api changes that stand out is that you can no longer roll back when in either of the have-remote-pranswer or the have-local-pranswer states. fortunately, when using perfect negotiation there's no need to do this anyway, since the situations that cause this are caught and prevented before rolling these back ever becomes necessary. thus, attempting to trigger rollback while in one of the two pranswer states will now throw an invalidstateerror. ...
Movement, orientation, and motion: A WebXR example - Web APIs
api's specification. by importing this polyfill, we allow the example to work on many browsers that don't yet have webxr implementations in place, and we smooth out any transient deviations from the specification that occur during these still somewhat experimental days of the webxr specification. options this example has a number of options you can configure by adjusting the values of constants before you load it in the browser. the code looks like this: const xrotationdegreespersecond = 25; const yrotationdegreespersecond = 15; const zrotationdegreespersecond = 35; const enablerotation = true; const allowmouserotation = true; const allowkeyboardmotion = true; const enableforcepolyfill = false; //const session_type = "immersive-vr"; const session_type = "inline"; const mouse_speed = 0.003; ...
...tly firing the end event. by running the event handler directly, we complete the close-out process manually in this situation. starting up the webxr session the sessionstarted() function handles actually setting up and starting the session, by setting up event handlers, compiling and installing the glsl code for the vertex and fragment shaders, and attaching the webgl layer to the webxr session before kicking off the rendering loop. it gets called as the handler for the promise returned by issessionsupported(). function sessionstarted(session) { let refspacetype; xrsession = session; xrbutton.innertext = "exit webxr"; xrsession.addeventlistener("end", sessionended); let canvas = document.queryselector("canvas"); gl = canvas.getcontext("webgl", { xrcompatible: true }); if (all...
...nvas is the right size to allow us to do this, we set its width to be equal to the individual xrview width multiplied by the number of views; the canvas height is always the same as the viewport's height. the two lines of code that adjust the canvas size are not needed in regular webxr rendering loops. applying the user inputs the applyviewercontrols() function, which is called by drawframe() before beginning to render anything, takes the offsets in each of the three directions, the yaw offset, and the pitch offset as recorded by the handlekeydown() and handlepointermove() functions in response to the user pressing keys and dragging their mouse with the right mouse button pressed. it takes as input the base reference space for the object, and returns a new reference space that alters the loc...
...the rest of the code is identical to that found in the earlier examples: initshaderprogram() initializes the glsl shader program, calling loadshader() to load and compile each shader's program, then attaching each one to the webgl context. once they're compiled, the program is linked and returned to the caller. loadshader() creates a shader object and loads the specified source code into it before compiling the code and checking to ensure that the compiler succeeded before returning the newly compiled shader to the caller. if an error occurs, nil is returned instead. initbuffers() initializes the buffers that contain data to be passed into webgl. these buffers include the array of vertex positions, the array of vertex normals, the texture coordinates for each surface of the cube, and the...
Using the Web Audio API - Web APIs
de functionality to play/pause the sound, alter the track's volume, and pan it from left to right. controlling sound programmatically from javascript code is covered by browsers' autoplay support policies, as such is likely to be blocked without permission being granted by the user (or a whitelist). autoplay policies typically require either explicit permission or a user engagement with the page before scripts can trigger audio to play. these special requirements are in place essentially because unexpected sounds can be annoying and intrusive, and can cause accessibility problems. you can learn more about this in our article autoplay guide for media and web audio apis. since our scripts are playing audio in response to a user input event (a click on a play button, for instance), we're in good...
...esponse to a user input event (a click on a play button, for instance), we're in good shape and should have no problems from autoplay blocking. so, let's start by taking a look at our play and pause functionality. we have a play button that changes to a pause button when the track is playing: <button data-playing="false" role="switch" aria-checked="false"> <span>play/pause</span> </button> before we can play our track we need to connect our audio graph from the audio source/input node to the destination. we've already created an input node by passing our audio element into the api. for the most part, you don't need to create an output node, you can just connect your other nodes to baseaudiocontext.destination, which handles the situation for you: track.connect(audiocontext.destination);...
...sing a gainnode, which represents how big our sound wave is. there are two ways you can create nodes with the web audio api. you can use the factory method on the context itself (e.g. audiocontext.creategain()) or via a constructor of the node (e.g. new gainnode()). we'll use the factory method in our code: const gainnode = audiocontext.creategain(); now we have to update our audio graph from before, so the input is connected to the gain, then the gain node is connected to the destination: track.connect(gainnode).connect(audiocontext.destination); this will make our audio graph look like this: the default value for gain is 1; this keeps the current volume the same. gain can be set to a minimum of about -3.4 and a max of about 3.4. here we'll allow the boombox to move the gain up to 2 (...
... creating nodes is not supported by all browsers at this time. the older factory methods are supported more widely. here our values range from -1 (far left) and 1 (far right). ...
Visualizations with Web Audio API - Web APIs
more information on how to use them. to capture data, you need to use the methods analysernode.getfloatfrequencydata() and analysernode.getbytefrequencydata() to capture frequency data, and analysernode.getbytetimedomaindata() and analysernode.getfloattimedomaindata() to capture waveform data. these methods copy data into a specified array, so you need to create a new array to receive the data before invoking one. the first one produces 32-bit floating point numbers, and the second and third ones produce 8-bit unsigned integers, therefore a standard javascript array won't do — you need to use a float32array or uint8array array, depending on what data you are handling. so for example, say we are dealing with an fft size of 2048. we return the analysernode.frequencybincount value, which is h...
...oscilloscope to create the oscilloscope visualisation (hat tip to soledad penadés for the original code in voice-change-o-matic), we first follow the standard pattern described in the previous section to set up the buffer: analyser.fftsize = 2048; var bufferlength = analyser.frequencybincount; var dataarray = new uint8array(bufferlength); next, we clear the canvas of what had been drawn on it before to get ready for the new visualization display: canvasctx.clearrect(0, 0, width, height); we now define the draw() function: function draw() { in here, we use requestanimationframe() to keep looping the drawing function once it has been started: var drawvisual = requestanimationframe(draw); next, we grab the time domain data and copy it into our array analyser.getbytetimedomaindata(dataarr...
...waveform display that updates several times a second: creating a frequency bar graph another nice little sound visualization to create is one of those winamp-style frequency bar graphs. we have one available in voice-change-o-matic; let's look at how it's done. first, we again set up our analyser and data array, then clear the current canvas display with clearrect(). the only difference from before is that we have set the fft size to be much smaller; this is so that each bar in the graph is big enough to actually look like a bar rather than a thin strand. analyser.fftsize = 256; var bufferlength = analyser.frequencybincount; console.log(bufferlength); var dataarray = new uint8array(bufferlength); canvasctx.clearrect(0, 0, width, height); next, we start our draw() function off, again sett...
...e 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 start a for loop and cycle through each value in the dataarray. for each one, we make the barheight equal to the array value, set a fill colour based on the barheight (taller bars are brighter), and draw a bar at x pixels across the canvas, which is barwidth wide and barheight/2 tall (we eventually decided to cut each bar in half so they would all fit on the canvas better.) the one value...
Using Web Workers - Web APIs
ipt and executes it. any global objects from each script may then be used by the worker. if the script can't be loaded, network_error is thrown, and subsequent code will not be executed. previously executed code (including code deferred using window.settimeout()) will still be functional though. function declarations after the importscripts() method are also kept, since these are always evaluated before the rest of the code. note: scripts may be downloaded in any order, but will be executed in the order in which you pass the filenames into importscripts() . this is done synchronously; importscripts() does not return until all the scripts have been loaded and executed. shared workers a shared worker is accessible by multiple scripts — even if they are being accessed by different windows, ifr...
...sharedworker('worker.js'); one big difference is that with a shared worker you have to communicate via a port object — an explicit port is opened that the scripts can use to communicate with the worker (this is done implicitly in the case of dedicated workers). ...
... before any messages can be posted. calling start() is only needed if the message event is wired up via the addeventlistener() method. note: when using the start() method to open the port connection, it needs to be called from both the parent thread and the worker thread if two-way communication is needed. sending messages to and from a shared worker now messages can be sent to the worker as before, but the postmessage() method has to be invoked through the port object (again, you'll see similar constructs in both multiply.js and square.js): squarenumber.onchange = function() { myworker.port.postmessage([squarenumber.value,squarenumber.value]); console.log('message posted to worker'); } now, on to the worker. there is a bit more complexity here as well (worker.js): onconnect = functi...
...sages can be sent to and from the main thread by using postmessage(), and the message event's data attribute contains data passed back from the worker. example.html: (the main page): var myworker = new worker('my_task.js'); myworker.onmessage = function(oevent) { console.log('worker said : ' + oevent.data); }; myworker.postmessage('ali'); my_task.js (the worker): postmessage("i\'m working before postmessage(\'ali\')."); onmessage = function(oevent) { postmessage('hi ' + oevent.data); }; the structured cloning algorithm can accept json and a few things that json can't — like circular references. passing data examples example #1: advanced passing json data and creating a switching system if you have to pass some complex data and have to call many different functions both on the ma...
Window.open() - Web APIs
Web › API › Window › open
be off. example: status=yes, status=1, and status have identical results. menubar if this feature is on, then the new secondary window renders the menubar. if windowfeatures is non-empty, menubar detaults to off. toolbar if this feature is on, then the new secondary window renders the toolbar buttons (back, forward, reload, stop buttons). in addition to the toolbar buttons, firefox (before 76) will render the tab bar if it is visible, present in the parent window. (if this feature is set to off, all toolbars in the window will be invisible). if windowfeatures is non-empty, toolbar detaults to off. location if this feature is on, then the new secondary window renders the location bar or the address bar. if windowfeatures is non-empty, location detaults to off. status if th...
...erty <property_name or method_name>. why is that? it is because of the cross-domain script security restriction (also referred as the "same origin policy"). a script loaded in a window (or frame) from a distinct origin (domain name) cannot get nor set properties of another window (or frame) or the properties of any of its html objects coming from another distinct origin (domain name). therefore, before executing a script targeting a secondary window, the browser in the main window will verify that the secondary window has the same domain name. more reading on the cross-domain script security restriction: http://www.mozilla.org/projects/secu...me-origin.html usability issues avoid resorting to window.open() generally speaking, it is preferable to avoid resorting to window.open() for several...
...n't notice that a new window has opened, especially if they are using a small monitor where the windows are maximized to fill up the screen. so a user who tries to return to the origin will be confused by a grayed out back button." quote from the top ten new mistakes of web design: 2. opening new browser windows, jakob nielsen, may 1999 when extreme changes in context are explicitly identified before they occur, then the users can determine if they wish to proceed or so they can be prepared for the change: not only they will not be confused or feel disoriented, but more experienced users can better decide how to open such links (in a new window or not, in the same window, in a new tab or not, in "background" or not). references "if your link spawns a new window, or causes another windows ...
...references "if your link spawns a new window, or causes another windows to 'pop up' on your display, or move the focus of the system to a new frame or window, then the nice thing to do is to tell the user that something like that will happen." world wide web consortium accessibility initiative regarding popups "use link titles to provide users with a preview of where each link will take them, before they have clicked on it." ten good deeds in web design, jakob nielsen, october 1999 using link titles to help users predict where they are going, jakob nielsen, january 1998 example "new window" icons & cursors always use the target attribute if javascript support is disabled or non-existent, then ...
Window: unload event - Web APIs
the unload event is fired when the document or a child resource is being unloaded. ...
...er: beforeunload (cancelable event) pagehide the document is in the following state: all the resources still exist (img, iframe etc.) nothing is visible anymore to the end user ui interactions are ineffective (window.open, alert, confirm, etc.) an error won't stop the unloading workflow please note that the unload event also follows the document tree: parent frame unload will happen before child frame unload (see example below). ...
...more to the end user ui interactions are ineffective (window.open, alert, confirm, etc.) an error won't stop the unloading workflow please note that the unload event also follows the document tree: parent frame unload will happen before child frame unload (see example below). ...
... specifications sp...
ARIA: listbox role - Accessibility
ore clearly identifies the role of the listbox. screen readers will often read this value to the user after reading the label (if there is one), in place of saying "listbox". ...
...of saying "listbox". (for further details and a full list of aria states and properties see the aria listbox (role) documentation.) keyboard interactions when a single-select listbox receives focus: if none of the options are selected before the listbox receives focus, the first option receives focus. optionally, the first option may be automatically selected. if an option is selected before the listbox receives focus, focus is set on the selected option. ...
... down arrow: moves focus to the next option. ...
... down arrow: moves focus to the next option. optionally, in a single-select listbox, selection may also move with focus. up arrow: moves focus to the previous option. ...
:valid - CSS: Cascading Style Sheets
Web › CSS › :valid
we then absolutely position different generated content dependi...
...we 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 ...
...t name *: </label> <input id="fname" name="fname" type="text" required> <span></span> </div> to provide these indicators, we use the following css: input + span { position: relative; } input + span::before { position: absolute; right: -20px; top: 5px; } input:invalid { border: 2px solid red; } input:invalid + span::before { content: '✖'; color: red; } input:valid + span::before { content: '✓'; color: green; } we set the <span>s to position: relative so that we can position the generated content relative to them. we 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 bor...
... we set the <span>s to position: relative so that we can position the generated content relative to them. we then absolutely position different generated content depending on whether the form's data is valid or invalid — a green check or a red cross, respectively. to add a bit of extra urgency to the invalid data, we've also given the inputs a thick red border when invalid. note: we've used ::before to add these labels, as we were already using ::after for the "required" labels. you can try it below: notice how the required text inputs are invalid when empty, but valid when they have something filled in. the email input on the other hand is valid when empty, as it is not required, but invalid when it contains something that is not a proper email address. accessibility concerns the col...
Controlling Ratios of Flex Items Along the Main Axis - CSS: Cascading Style Sheets
fully understanding how these properties work with growing and shrinking items is the real key to mastering flexbox. a first look our three properties control the following aspects of a flex item's flexibility: flex-grow: how much of the positive free space does this item get? flex-shrink: how much negative free space can be removed from this item? flex-basis: what is the size of the item before growing and shrinking happens? the properties are usually expressed as the shorthand flex property. the following code would set the flex-grow property to 2, flex-shrink to 1 and flex-basis to auto. .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. here we will explore them in depth in order th...
...rink to 1 and flex-basis to auto. .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. here we will explore them in depth in order that you can fully understand what the browser is doing when you use them. important concepts when working on the main axis there are a few concepts worth digging into before looking at how the flex properties work to control ratios along the main axis. these relate to the natural size of flex items before any growing or shrinking takes place, and to the concept of free space. flex item sizing in order to work out how much space there is available to lay out flex items, the browser needs to know how big the item is to start with. how is this worked out for items tha...
...l width of all the items with the container width. you could equally try out each example with flex-direction: column. the main axis would then be the column, and you would then need to compare the height of the items and that of the container they are in to work out the positive and negative free space. the flex-basis property the flex-basis property specifies the initial size of the flex item before any space distribution happens. the initial value for this property is auto. if flex-basis is set to auto then to work out the initial size of the item the browser first checks if the main size of the item has an absolute size set. this would be the case if you had given your item a width of 200 pixels. in that case 200px would be the flex-basis for this item. if your item is instead auto-sized,...
...e it is usually subtle, defined in the specification is one reason why flex-shrink isn’t quite the same for negative space as flex-grow is for positive space: “note: the flex shrink factor is multiplied by the flex base size when distributing negative space. this distributes negative space in proportion to how much the item is able to shrink, so that e.g. a small item won’t shrink to zero before a larger item has been noticeably reduced.” the second reason is that flexbox prevents small items from shrinking to zero size during this removal of negative free space. the items will be floored at their min-content size — the size that they become if they take advantage of any soft wrapping opportunities available to them. you can see this min-content flooring happen in the below exampl...
Using CSS transitions - CSS: Cascading Style Sheets
{ transition-property: opacity, left; transition-duration: 3s, 5s, 2s, 1s; } this gets interpreted as: div { transition-property: opacity, left; transition-duration: 3s, 5s; } using transitions when highlighting menus a common use of css is to highlight items in a menu as the user hovers the mouse cursor over them. it's easy to use transitions to make the effect even more attractive. before we look at code snippets, you might want to take a look at the live demo (assuming your browser supports transitions). first, we set up the menu using html: <nav> <a href="#">home</a> <a href="#">about</a> <a href="#">contact us</a> <a href="#">links</a> </nav> then we build the css to implement the look and feel of our menu. the relevant portions are shown here: a { color: #fff; ...
...javascript examples care should be taken when using a transition immediately after: adding the element to the dom using .appendchild() removing an element's display: none; property. this is treated as if the initial state had never occurred and the element was always in its final state. the easy way to overcome this limitation is to apply a window.settimeout() of a handful of milliseconds before changing the css property you intend to transition to. using transitions to make javascript functionality smooth transitions are a great tool to make things look much smoother without having to do anything to your javascript functionality. take the following example. <p>click anywhere to move the ball</p> <div id="foo"></div> using javascript you can make the effect of moving the ball to a ...
...ompleted. elapsedtime a float indicating the number of seconds the transition had been running at the time the event fired. this value isn't affected by the value of transition-delay. ...
...tener("transitionend", updatetransition, true); you detect the beginning of a transition using transitionrun (fires before any delay) and transitionstart (fires after any delay), in the same kind of fashion: el.addeventlistener("transitionrun", signalstart, true); el.addeventlistener("transitionstart", signalstart, true); note: the transitionend event doesn't fire if the transition is aborted before the transition is completed because either the element is made display: none or the animating property's value is changed. specifications specification status comment css transitions working draft initial definition ...
CSS reference - CSS: Cascading Style Sheets
Web › CSS › Reference
elayanimation-directionanimation-durationanimation-fill-modeanimation-iteration-countanimation-nameanimation-play-stateanimation-timing-function@annotationannotation()attr()b::backdropbackdrop-filterbackface-visibilitybackgroundbackground-attachmentbackground-blend-modebackground-clipbackground-colorbackground-imagebackground-originbackground-positionbackground-repeatbackground-size<basic-shape>::before (:before)bleed (@page)<blend-mode>block-sizeblur()borderborder-blockborder-block-colorborder-block-endborder-block-end-colorborder-block-end-styleborder-block-end-widthborder-block-startborder-block-start-colorborder-block-start-styleborder-block-start-widthborder-block-styleborder-block-widthborder-bottomborder-bottom-colorborder-bottom-left-radiusborder-bottom-right-radiusborder-bottom-stylebor...
...leftborder-left-colorborder-left-styleborder-left-widthborder-radiusborder-rightborder-right-colorborder-right-styleborder-right-widthborder-spacingborder-start-end-radiusborder-start-start-radiusborder-styleborder-topborder-top-colorborder-top-left-radiusborder-top-right-radiusborder-top-styleborder-top-widthborder-widthbottom@bottom-centerbox-decoration-breakbox-shadowbox-sizingbreak-afterbreak-beforebreak-insidebrightness()ccalc()caption-sidecaret-colorch@character-variantcharacter-variant()@charset:checkedcircle()clamp()clearclipclip-pathcm<color>colorcolor-adjustcolumn-countcolumn-fillcolumn-gapcolumn-rulecolumn-rule-colorcolumn-rule-stylecolumn-rule-widthcolumn-spancolumn-widthcolumnsconic-gradient()containcontentcontrast()<counter>counter-incrementcounter-resetcounter-set@counter-stylecou...
...overflow-anchoroverflow-blockoverflow-inlineoverflow-wrapoverflow-xoverflow-yoverscroll-behavioroverscroll-behavior-blockoverscroll-behavior-inlineoverscroll-behavior-xoverscroll-behavior-yppad (@counter-style)paddingpadding-blockpadding-block-endpadding-block-startpadding-bottompadding-inlinepadding-inline-endpadding-inline-startpadding-leftpadding-rightpadding-top@pagepage-break-afterpage-break-beforepage-break-insidepaint()paint-orderpath()pc<percentage>perspectiveperspective()perspective-originplace-contentplace-itemsplace-self::placeholderpointer-eventspolygon()<position>positionprefix (@counter-style)ptpxqqquotesrradradial-gradient()range (@counter-style)<ratio>:read-only:read-writerect()remrepeat()repeating-linear-gradient()repeating-radial-gradient():requiredresize<resolution>revertrgb()...
...is a child of b" or "a is adjacent to b." adjacent sibling combinator a + b specifies that the elements selected by both a and b have the same parent and that the element selected by b immediately follows the element selected by a horizontally. general sibling combinator a ~ b specifies that the elements selected by both a and b share the same parent and that the element selected by a comes before—but not necessarily immediately before—the element selected by b. child combinator a > b specifies that the element selected by b is the direct child of the element selected by a. descendant combinator a b specifies that the element selected by b is a descendant of the element selected by a, but is not necessarily a direct child. column combinator a || b specifies that the element sel...
position - CSS: Cascading Style Sheets
Web › CSS › position
xploreroperasafariandroid webviewchrome for androidfirefox for androidopera for androidsafari on iossamsung internetpositionchrome full support 1edge full support 12firefox full support 1notes full support 1notes notes before firefox 57, absolute positioning did not work correctly when applied to elements inside tables that have border-collapse applied to them (bug 1379306).notes before firefox 30, absolute positioning of table rows and row groups was not supported (bug 63895).ie full support 4opera full support 4safari ...
... 4safari full support 1webview android full support ≤37chrome android full support 18firefox android full support 4notes full support 4notes notes before firefox 57, absolute positioning did not work correctly when applied to elements inside tables that have border-collapse applied to them (bug 1379306).notes before firefox 30, absolute positioning of table rows and row groups was not supported (bug 63895).opera android full support 14safari ios full support ...
...firefox and the specification have been modified to mimic chrome and safari's long-time behavior.ie full support 7notes full support 7notes notes in internet explorer, fixed positioning doesn't work if the document is in quirks mode...
...firefox and the specification have been modified to mimic chrome and safari's long-time behavior.opera android full support 14safari ios full support 1samsung internet android full support ...
will-change - CSS: Cascading Style Sheets
important: will-change is intended to be used as a last resort, in order to try to deal with existing performance problems. it should not be used to anticipate performance problems. ...
... important: will-change is intended to be used as a last resort, in order to try to deal with existing performance problems. it should not be used to anticipate performance problems. ...
...ons 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 have otherwise. so it is a good practice to switch will-change on and off using script code before and after the change occurs. don't apply will-change to elements to perform premature optimization. if your page is performing well, don't add the will-change property to elements just to wring out a little more speed. will-change is intended to be used as something of a last resort, in order to try to deal with existing performance problems. it should not be used to anticipate performance ...
...complex rendering to occur as the browser attempts to prepare for the possible change. this will lead to worse performance. give it sufficient time to work. this property is intended as a method for authors to let the user-agent know about properties that are likely to change ahead of time. then the browser can choose to apply any ahead-of-time optimizations required for the property change before the property change actually happens. so it is important to give the browser some time to actually do the optimizations. find some way to predict at least slightly ahead of time that something will change, and set will-change then. be aware, that will-change may actually influence the visual appearance of elements, when used with property values, that create a stacking context (e.g. will-ch...
Cross-browser audio basics - Developer guides
type is used to inform the browser of the file type. if omitted, most browsers will attempt to guess this from the file extension. if the <audio> element is not supported then <audio> and <source> will be ignored. however any supported text or elements that you define within <audio> will be displayed or acted upon. so the ideal place to create a fallback or inform of incompatibility is before the closing </audio> tag. in this case, 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 funct...
...dio 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. preload the preload attribute allows you to specify a preference for how the browser preloads the audio, in other words, which part of the file it downloads when the <audio> element is initialized, and before the play button is pressed. preload can take 3 different values: none: don't download anything before the play button is pressed. metadata: download the audio metadata; this is usually the best option, as it allows you to access and display information such as audio length, and allow the browser to work out which audio file it should use. auto: download the whole audio file as soon as possi...
...is established, this is the event for you. this can be useful because the initial value for duration is nan (not a number), which you probably don't want to display to your users. myaudio.addeventlistener("durationchange", function() { //you can display the duration now }); loadedmetadata metadata can consist of more than just duration — if you want to wait for all the metadata to download before doing something, you can detect the loadedmetadata event. myaudio.addeventlistener("loadedmetadata", function() { //you can display the duration now }); loadeddata the loadeddata event is fired when the first bit of media arrives. the playhead is in position but not quite ready to play. myaudio.addeventlistener("loadeddata", function() { //you could display the playhead now }); progress ...
...{ var myaudio = document.getelementbyid('my-audio'); var play = document.getelementbyid('play'); var pause = document.getelementbyid('pause'); var loading = document.getelementbyid('loading'); var bar = document.getelementbyid('bar'); function displaycontrols() { loading.style.display = "none"; play.style.display = "block"; } // check that the media is ready before displaying the controls if (myaudio.paused) { displaycontrols(); } else { // not ready yet - wait for canplay event myaudio.addeventlistener('canplay', function() { displaycontrols(); }); } play.addeventlistener('click', function() { myaudio.play(); play.style.display = "none"; pause.style.display = "block"; }); pause.addevent...
<input>: The Input (Form Input) element - HTML: Hypertext Markup Language
Web › HTML › Element › input
luding information on password security and how autocomplete is slightly different for hidden than for other input types. autofocus a boolean attribute which, if present, indicates that the input should automatically have focus when the page has finished loading (or when the <dialog> containing the element has been displayed). note: an element with the autofocus attribute may gain focus before the domcontentloaded event is fired. no more than one element in the document may have the autofocus attribute. if put on more than one element, the first one with the attribute receives focus. the autofocus attribute cannot be used on inputs of type hidden, since hidden inputs cannot be focused. warning: automatically focusing a form control can confuse visually-impaired people using s...
...he attribute receives focus. the autofocus attribute cannot be used on inputs of type hidden, since hidden inputs cannot be focused. warning: automatically focusing a form control can confuse visually-impaired people using screen-reading technology and people with cognitive impairments. ...
... without warning them beforehand. use careful consideration for accessibility when applying the autofocus attribute. automatically focusing on a control can cause the page to scroll on load. the focus can also cause dynamic keyboards to display on some touch devices. while a screen reader will announce the label of the form control receiving focus, the screen reader will not announce anything before the label, and the sighted user on a small device will equally miss the context created by the preceding content. capture introduced in the html media capture specification and valid for the file input type only, the capture attribute defines which media—microphone, video, or camera—should be used to capture a new file for upload with file upload control in supporting scenarios. see the...
... indicates that the user should not be able to edit the value of the input. the readonly attribute is supported text, search, url, tel, email, date, month, week, time, datetime-local, number, and password input types. see the html attribute: readonly for more information. required required is a boolean attribute which, if present, indicates that the user must specify a value for the input before the owning form can be submitted. the required attribute is supported text, search, url, tel, email, date, month, week, time, datetime-local, number, password, checkbox, radio, and file. see client-side validation and the html attribute: required for more information. size valid for email, password, tel, and text input types only. specifies how much of the input is shown. basically creates ...
<script>: The Script element - HTML: Hypertext Markup Language
Web › HTML › Element › script
luated as soon as it is available. for module scripts, if the async attribute is present then the scripts and all their dependencies will be executed in the defer queue, therefore they will get fetched in parallel to parsing and evaluated as soon as they are available. this attribute allows the elimination of parser-blocking javascript where the browser would have to load and evaluate scripts before continuing to parse. defer has a similar effect in this case. this is a boolean attribute: the presence of a boolean attribute on an element represents the true value, and the absence of the attribute represents the false value. see browser compatibility for notes on browser support. see also async scripts for asm.js. crossorigin normal script elements pass minimal information to the wind...
...dow.onerror for scripts which do not pass the standard cors checks. to allow error logging for sites which use a separate domain for static media, use this attribute. see cors settings attributes for a more descriptive explanation of its valid arguments. defer this boolean attribute is set to indicate to a browser that the script is meant to be executed after the document has been parsed, but before firing domcontentloaded. scripts with the defer attribute will prevent the domcontentloaded event from firing until the script has loaded and finished evaluating. this attribute must not be used if the src attribute is absent (i.e. for inline scripts), in this case it would have no effect. the defer attribute has no effect on module scripts — they defer by default. scripts with the ...
... src attribute is absent (i.e. for inline scripts), in this case it would have no effect. the defer attribute has no effect on module scripts — they defer by default. scripts with the defer attribute will execute in the order in which they appear in the document. this attribute allows the elimination of parser-blocking javascript where the browser would have to load and evaluate scripts before continuing to parse. async has a similar effect in this case. integrity this attribute contains inline metadata that a user agent can use to verify that a fetched resource has been delivered free of unexpected manipulation. see subresource integrity. nomodule this boolean attribute is set to indicate that the script should not be executed in browsers that support es2015 modules — in effec...
...cter encoding from the document. language like the type attribute, this attribute identifies the scripting language in use. unlike the type attribute, however, this attribute’s possible values were never standardized. the type attribute should be used instead. notes scripts without async , defer or type="module" attributes, as well as inline scripts, are fetched and executed immediately, before the browser continues to parse the page. the script should be served with the text/javascript mime type, but browsers are lenient and only block them if the script is served with an image type (image/*); a video type (video/*); an audio (audio/*) type; or text/csv. if the script is blocked, an error is sent to the element, if not a load event is sent. examples basic usage these examples show ...
A re-introduction to JavaScript (JS tutorial) - JavaScript
} javascript also contains two other prominent for loops: for...of for (let value of array) { // do something with value } and for...in: for (let property in object) { // do something with object property } the && and || operators use short-circuit logic, which means whether they will execute their second operand is dependent on the first. ...
...nction avg(...args) { var sum = 0; for (let value of args) { sum += value; } return sum / args.length; } avg(2, 3, 4, 5); // 3.5 in the above code, the variable args holds all the values that were passed into the function. it is important to note that wherever the rest parameter operator is placed in a function declaration it will store all arguments after its declaration, but not before. i.e. function avg(firstvalue, ...args) will store the first value passed into the function in the firstvalue variable and the remaining arguments in args. that's another useful language feature but it does lead us to a new problem. the avg() function takes a comma-separated list of arguments — but what if you want to find the average of an array? you could just rewrite the function as follows:...
...the root of that chain is object.prototype, whose methods include tostring() — it is this method that is called when you try to represent an object as a string. this is useful for debugging our person objects: var s = new person('simon', 'willison'); s.tostring(); // [object object] person.prototype.tostring = function() { return '<person: ' + this.full...
... again lets you set this but takes an expanded argument list as opposed to an array. function lastnamecaps() { return this.last.touppercase(); } var s = new person('simon', 'willison'); lastnamecaps.call(s); // is the same as: s.lastnamecaps = lastnamecaps; s.lastnamecaps(); // willison inner functions javascript function declarations are allowed inside other functions. we've seen this once before, with an earlier makeperson() function. an important detail of nested functions in javascript is that they can access variables in their parent function's scope: function parentfunc() { var a = 1; function nestedfunc() { var b = 4; // parentfunc can't use this return a + b; } return nestedfunc(); // 5 } this provides a great deal of utility in writing more maintainable code. i...
Promise - JavaScript
se. the fulfillment of the promise is simply logged, via a fulfill callback set using p1.then(). a few logs show how the synchronous part of the method is decoupled from the asynchronous completion of the promise. ...
...ment.getelementbyid('log'); // begin log.insertadjacenthtml('beforeend', thispromisecount + ') started (sync code started)'); // we make a new promise: we promise a numeric count of this promise, starting from 1 (after waiting 3s) let p1 = new promise((resolve, reject) => { // the executor function is called with the ability to resolve or reject the promise log.insertadjacenthtml('beforeend', thispromisecount + ') promise started (async code started)'); // this is only an example to create asynchronism window.settimeout(function() { // we fulfill the promise ! resolve(thispromisecount); }, math.random() * 2000 + 1000); }); // we define what to do when the promise is resolved with the then() call, // and what to do when the promise is rejected wi...
...e asynchronism window.settimeout(function() { // we fulfill the promise ! ...
...he then() call, // and what to do when the promise is rejected with the catch() call p1.then(function(val) { // log the fulfillment value log.insertadjacenthtml('beforeend', val + ') promise fulfilled (async code terminated)'); }).catch((reason) => { // log the rejection reason console.log(`handle rejected promise (${reason}) here.`); }); // end log.insertadjacenthtml('beforeend', thispromisecount + ') promise made (sync code terminated)'); } if ("promise" in window) { let btn = document.getelementbyid("btn"); btn.addeventlistener("click",testpromise); } else { log = document.getelementbyid('log'); log.innerhtml = "live example not available as your browser doesn't support the <code>promise<code> interface."; } this example is started by clicking the bu...
String.prototype.replace() - JavaScript
nondigits, p2 digits, and p3 non-alphanumerics return [p1, p2, p3].join(' - '); } let newstring = 'abc12345#$*%'.replace(/([^\d]*)(\d*)([^\w]*)/, replacer); console.log(newstring); // abc - 12345 - #$*% examples defining the regular expression in replace() in the following example, the regular expression is defined in replace() and includes the ignore case flag. let str = 'twas the night before xmas...'; let newstr = str.replace(/xmas/i, 'christmas'); console.log(newstr); // twas the night before christmas... this logs 'twas the night before christmas...'. note: see this guide for more explanations about regular expressions. using global and ignore with replace() global replace can only be done with a regular expression. in the following example, the regular expression includes ...
...capturing groups and the $1 and $2 replacement patterns. let re = /(\w+)\s(\w+)/; let str = 'john smith'; let newstr = str.replace(re, '$2, $1'); console.log(newstr); // smith, john this logs 'smith, john'. using an inline function that modifies the matched characters in this example, all occurrences of capital letters in the string are converted to lower case, and a hyphen is inserted just before the match location. the important thing here is that additional operations are needed on the matched item before it is given back as a replacement. the replacement function accepts the matched snippet as its parameter, and uses it to transform the case and concatenate the hyphen before returning. function stylehyphenformat(propertyname) { function uppertohyphenlower(match, offset, string) { ...
...this forces the evaluation of the match prior to the tolowercase() method. if we had tried to do this using the match without a function, the tolowercase() would have no effect. ...
...must use a function. this forces the evaluation of the match prior to the tolowercase() method. if we had tried to do this using the match without a function, the tolowercase() would have no effect. let newstring = propertyname.replace(/[a-z]/g, '-' + '$&'.tolowercase()); // won't work this is because '$&'.tolowercase() would first be evaluated as a string literal (resulting in the same '$&') before using the characters as a pattern. replacing a fahrenheit degree with its celsius equivalent the following example replaces a fahrenheit degree with its equivalent celsius degree. the fahrenheit degree should be a number ending with "f". the function returns the celsius number ending with "c". for example, if the input number is "212f", the function returns "100c". if the number is "0f", the fu...
var - JavaScript
e https://github.com/mdn/interactive-examples and send us a pull request. syntax var varname1 [= value1] [, varname2 [= value2] ... [, varnamen [= valuen]]]; varnamen variable name. it can be any legal identifier. valuen optional initial value of the variable. it can be any legal expression. default value is undefined. description var declarations, wherever they occur, are processed before any code is executed. this is called hoisting, and is discussed further below. the scope of a variable declared with var is its current execution context and closures thereof, which is either the enclosing function and functions declared within it, or, for variables declared outside any function, global. duplicate variable declarations using var will not trigger an error, even in strict mode, an...
...less another assignment is performed. 'use strict'; function foo() { var x = 1; function bar() { var y = 2; console.log(x); // 1 (function `bar` closes over `x`) console.log(y); // 2 (`y` is in scope) } bar(); console.log(x); // 1 (`x` is in scope) console.log(y); // referenceerror in strict mode, `y` is scoped to `bar` } foo(); variables declared using var are created before any code is executed in a process known as hoisting. their initial value is undefined. 'use strict'; console.log(x); // undefined (note: not referenceerror) console.log('still going...'); // still going... var x = 1; console.log(x); // 1 console.log('still going...'); // still going... in the global context, a variable declared using var is added as a non-configura...
... in strict mode will result in a referenceerror, to avoid the accidental creation of properties on the global object. note that the implication of the above, is that, contrary to popular misinformation, javascript does not have implicit or undeclared variables, it merely has a syntax that looks like it does. var hoisting because variable declarations (and declarations in general) are processed before any code is executed, declaring a variable anywhere in the code is equivalent to declaring it at the top. this also means that a variable can appear to be used before it's declared. this behavior is called "hoisting", as it appears that the variable declaration is moved to the top of the function or global code. bla = 2; var bla; // ...is implicitly understood as: var bla; bla = 2; for that ...
...at the time "x = y" is evaluated, y exists so no referenceerror is thrown and its value is undefined. so, x is assigned the undefined value. then, y is assigned the value 'a'. consequently, after the first line, x === undefined && y === 'a', hence the result. initialization of several variables var x = 0; function f() { var x = y = 1; // ...
Codecs used by WebRTC - Web media technologies
's of additional importance when videoconferencing in order to ensure that the participants are able to communicate without lag or interruptions. of secondary importance is the need to keep the video and audio synchronized, so that the movements and any ancillary information (such as slides or a projection) are presented at the same time as the audio that corresponds. general codec requirements before looking at codec-specific capabilities and requirements, there are a few overall requirements that must be met by any codec configuration used with webrtc. unless the sdp specifically signals otherwise, the web browser receiving a webrtc video stream must be able to handle video at at least 20 fps at a minimum resolution of 320 pixels wide by 240 pixels tall. it's encouraged that video be encode...
...fault—or, more accurately, preferred—codecs requested by each browser's implementation of webrtc are shown in the table below. preferred codecs for webrtc in major web browsers audio video chrome edge firefox vp9 (firefox 46 and later) vp8 opera safari choosing the right codec before choosing a codec that isn't one of the mandatory codecs (vp8 or avc for video and opus or pcm for audio), you should seriously consider the potential drawbacks: in particular, only these codecs can be generally assumed to be available on essentially all devices that support webrtc. if you choose to prefer a codec other than the mandatory ones, you should at least allow for fallback to one of the...
...ment, using g.711 at an 8 khz sample rate can provide an acceptable experience for conversation, but typically you'll use g.711 as a fallback option, since there are other options which are more efficient and sound better, such as opus in its narrowband mode. video there are a number of factors that come into play when deciding upon a video codec (or set of codecs) to support. licensing terms before choosing a video codec, make sure you're aware of any licensing requirements around the codec you select; you can find information about possible licensing concerns in our main guide to video codecs used on the web. of the two mandatory codecs for video—vp8 and avc/h.264—only vp8 is completely free of licensing requirements. if you select avc, make sure you're; aware of any potential fees you...
...u're; aware of any potential fees you may need to pay; that said, the patent holders have generally said that most typical web site developers shouldn't need to worry about paying the license fees, which are typically focused more on the developers of the encoding and decoding software. warning: the information here does not constitute legal advice! be sure to confirm your exposure to liability before making any final decisions where potential exists for licensing issues. power needs and battery life another factor to consider—especially on mobile platforms—is the impact a codec may have on battery life. if a codec is handled in hardware on a given platform, that codec is likely to allow for much better battery life and less heat production. for example, safari for ios and ipados intro...
Populating the page: how browsers work - Web Performance
he distance between a phone, a cell tower, and the name server can add significant latency. tcp handshake once the ip address is known, the browser sets up a connection to the server via a tcp three-way handshake. this mechanism is designed so that two entities attempting to communicate—in this case the browser and web server—can negotiate the parameters of the network tcp socket connection before transmitting data, often over https. tcp's three way handshaking technique is often referred to as "syn-syn-ack"—or more accurately syn, syn-ack, ack—because there are three messages transmitted by tcp to negotiate and start a tcp session between two computers. yes, this means three more messages back and forth between each server, and the request has yet to be made. tls negotiation for se...
...ters. yes, this means three more messages back and forth between each server, and the request has yet to be made. tls negotiation for secure connections established over https, another "handshake" is required. this handshake, or rather the tls negotiation, determines which cipher will be used to encrypt the communication, verifies the server, and establishes that a secure connection is in place before beginning the actual transfer of data. this requires three more round trips to the server before the request for content is actually sent. while making the connection secure adds time to the page load, a secure connection is worth the latency expense, as the data transmitted between the browser and the web server cannot be decrypted by a third party. after the 8 round trips, the browser is fi...
... request page's html is larger than the initial 14kb packet, the browser will begin parsing and attempting to render an experience based on the data it has. this is why it's important for web performance optimization to include everything the browser needs to start rendering a page, or at least a template of the page - the css and html needed for the first render -- in the first 14 kilobytes. but before anything is rendered to the screen, the html, css, and javascript have to be parsed. building the dom tree we describe five steps in the critical rendering path. the first step is processing the html markup and building the dom tree. html parsing involves tokenization and tree construction. html tokens include start and end tags, as well as attribute names and values. if the document is well-f...
...the dimensions of all the body’s descendants, with each element's box model properties, providing placeholder space for replaced elements it doesn’t know the dimensions of, such as our image. the first time the size and position of nodes are determined is called layout. subsequent recalculations of node size and locations are called reflows. in our example, suppose the initial layout occurs before the image is returned. since we didn't declare the size of our image, there will be a reflow once the image size is known. paint the last step in the critical rendering path is painting the individual nodes to the screen, the first occurence of which is called the first meaningful paint. in the painting or rasterization phase, the browser converts each box calculated in the layout phase to actu...
Add to Home screen - Progressive web apps (PWAs)
to be used when there is insufficient space to display the full name. you are advised to provide both if your app's name is particularly long. start_url: provides a path to the asset that should be loaded when the added-to-home screen app is launched. note that this has to be a relative url pointing to the site index, relative to the url of the manifest. also, be aware that chrome requires this before it will display the install banner, whereas firefox doesn't require it for showing the home-with-a-plus icon. the manifest for our sample app looks like this: { "background_color": "purple", "description": "shows random fox pictures. hey, at least it isn't cats.", "display": "fullscreen", "icons": [ { "src": "icon/fox-icon.png", "sizes": "192x192", "type": "image/...
...dprompt variable (which we'll explain later on), get a reference to our install button, and set it to display: none initially: let deferredprompt; const addbtn = document.queryselector('.add-button'); addbtn.style.display = 'none'; we hide the button initially because the pwa will not be available for install until it follows the a2hs criteria. when this happens, supporting browsers will fire a beforeinstallprompt event. we can then use a handler like the one below to handle the installation: window.addeventlistener('beforeinstallprompt', (e) => { // prevent chrome 67 and earlier from automatically showing the prompt e.preventdefault(); // stash the event so it can be triggered later. deferredprompt = e; // update ui to notify the user they can add to home screen addbtn.style.disp...
... the deferredprompt variable so it can be used later on to perform the actual installation. set the button to display: block so it appears in the ui for the user to click. set a click handler for the button. the click handler contains the following steps: hide the button again with display: none — it is no longer needed once the app is installed. use the prompt() method available on the beforeinstallprompt event object (stored in deferredprompt) to trigger showing the install prompt. respond to the user's interaction with the prompt using the userchoice property, again available on the beforeinstallprompt event object. set deferredprompt to null since it is no longer needed. so when the button is clicked, the install prompt appears. if the user selects install, the app is instal...
...pt. respond to the user's interaction with the prompt using the userchoice property, again available on the beforeinstallprompt event object. set deferredprompt to null since it is no longer needed. so when the button is clicked, the install prompt appears. if the user selects install, the app is installed (available as standalone desktop app), and the install button no longer shows (the onbeforeinstallprompt event no longer fires if the app is already installed). when you open the app, it will appear in its own window: if the user selects cancel, the state of the app goes back to how it was before the button was clicked. note: the code for this section was mostly taken from app install banners/add to home screen by pete lepage. ...
Mobile first - Progressive web apps (PWAs)
this article offers some related ideas, looking at the concept of mobile first — the practice of designing a website so that the default layout/configuration is for mobile devices, and layouts and features for desktop browsers are then layered on top of that default. this guide looks at a few useful techniques inside the mobile first umbrella. ...
...red on top of that default. this guide looks at a few useful techniques inside the mobile first umbrella. first things first — mobile as a default you may think that concentrating on the mobile experience first sounds pointless, as we are more used to dealing with desktop sites, and we surely need to consider the full gamut of features for the overall experience across desktop, mobile, etc., before then paring it down to a mobile experience that is simpler, more streamlined, or whatever. this rings true, yes, but in our experience mobile first is more about having the mobile implementation as a default layer to build on. we consider the overall experience during the planning stage, look at what subset of features will be available on mobile, desktop, etc. in tandem and how they will be imp...
...xperience mobile first is more about having the mobile implementation as a default layer to build on. we consider the overall experience during the planning stage, look at what subset of features will be available on mobile, desktop, etc. in tandem and how they will be implemented. then at implementation stage, we present the mobile layout and functionality as the default configuration provided, before additional information is loaded on top of that, whenever appropriate. this means that mobiles (often the target devices with the least available memory, bandwidth or processing power available) can be given an experience suitable for them as quickly as possible, and as free as possible of extraneous information. for example: if you are serving different styling and layout information for diff...
...evices with the least available memory, bandwidth or processing power available) can be given an experience suitable for them as quickly as possible, and as free as possible of extraneous information. for example: if you are serving different styling and layout information for different viewport sizes, etc., it makes more sense to include the narrow screen/mobile styling as the default styling before any media queries are encountered, rather than having desktop/wider screen styling first. this way, mobile devices don't have to load assets and other information twice. if you are using mechanisms like feature detection and matchmedia to conditionally load scripting functionality depending on viewport size, feature support, etc., you should just load the very basics that pretty much all browser...
The building blocks of responsive design - Progressive web apps (PWAs)
mns all left. this way they end up side-by-side, and their proportions remain the same as the browser window size varies. this is just a simple grid example, but you can apply this principle to more complex grid layouts as required. border-box sizing the padding does not affect the overall width and height of the containers because we have set the box-sizing of all elements to border-box: *, *:before, *:after { -webkit-box-sizing: border-box; -moz-box-sizing: border-box; box-sizing: border-box; } this basically means that width and height will now set the dimensions of an element all the way up to and including the border, not just the content. so if you set width: 40%, the box width will always be 40% of its parent, and any padding and border widths set on the box will be subtracted f...
...ayout problem, and this can be done using media queries. note: media queries are a css3 feature that allow you to selectively apply css depending on the results of media feature tests — for more on the basics, read media queries. typical desktop layout in our example, we have a desktop layout, as we've already seen. this is created using the css rules included at the top of the stylesheet, before any media queries are encountered. mid-width layout we also have a mid-width layout, which is aimed at working well on tablets and narrow laptop screens. this is created by all of the css inside the first media query: @media all and (max-width: 1024px) { x-card:nth-child(1), x-card:nth-child(2) { width: 50%; } x-card:nth-child(3) { width: 100%; clear: left; } x-card...
...lution screen, so devices often apply a default zoom factor to rendered pages to avoid this. the trouble with this, then, is that raster images are zoomed in and as a result can start to look pixellated. css background images for css background images this is a fairly easy problem to solve. if you use the mobile first methodology, you will be creating your mobile layout inside your default css, before any media queries have been applied. the media queries then supply css that is only applied to the markup when the viewport is above a certain width. let's look at a quick example: header { height: 300px; width: 100%; background: url(images/small-header.jpg) center; } @media all and (min-width: 480px) { header { background: url(images/large-header.jpg) center; } } this means that...
...ich one is right for your particular situation. some available solutions are as follows: hisrc a jquery plugin that allows you to create small, medium, and large versions of an image, and then serves the appropriate one according to the browser's resolution and available network speed. mobify.js capturing a very clever technique from mozilla that allows you to capture the source of the page before it's parsed. this way, you can swap out image src values with javascript depending on browser features, circumventing browser preloading issues. this is promising, but doesn't work very well across older browsers. picturefill a javascript-based polyfill for <picture>, which works nicely, but it does require a lot of custom markup. adaptive images a server-side solution, which records the view...
alignment-baseline - SVG: Scalable Vector Graphics
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. as a presentation attribute, it can be applied to any element but it has effect only on the following four elements: <tspan>, <tref>, <altglyph>, and <textpath> usage notes value auto | baseline | before-edge | text-before-edge | middle | central | after-edge | text-after-edge | ideographic | alphabetic | hanging | mathematical | top | center | bottom default value auto animatable yes auto the value is the dominant-baseline of the script to which the character belongs - i.e., use the dominant-baseline of the parent. baseline uses the dominant baseline choice ...
...raphic | alphabetic | hanging | mathematical | top | center | bottom default value auto animatable yes auto the value is the dominant-baseline of the script to which the character belongs - i.e., use the dominant-baseline of the parent. baseline uses the dominant baseline choice of the parent. matches the box’s corresponding baseline to that of its parent. before-edge the alignment-point of the object being aligned is aligned with the "before-edge" baseline of the parent text content element. text-bottom matches the bottom of the box to the top of the parent’s content area. text-before-edge the alignment-point of the object being aligned is aligned with the "text-before-edge" baseline of the parent text content element. note: this keyword may...
...he box’s mathematical baseline to that of its parent. top aligns the top of the aligned subtree with the top of the line box. center aligns the center of the aligned subtree with the center of the line box. bottom aligns the bottom of the aligned subtree with the bottom of the line box. svg 2 introduces some changes to the definition of this property. in particular: the values auto, before-edge, and after-edge have been removed. for backwards compatibility, text-before-edge may be mapped to text-top and text-after-edge to text-bottom. neither text-before-edge nor text-after-edge should be used with the vertical-align property. example <svg width="300" height="120" viewbox="0 0 300 120" xmlns="http://www.w3.org/2000/svg"> <!-- materialisation of anchors --> <path d="...
...line. specifications specification status comment css inline layoutthe definition of 'alignment-baseline' in that specification. working draft no change scalable vector graphics (svg) 2the definition of 'alignment-baseline' in that specification. candidate recommendation refers to the definition in css inline layout and notes the changes to auto, before-edge, after-edge, text-before-edge, and text-after-edge scalable vector graphics (svg) 1.1 (second edition)the definition of 'alignment-baseline' in that specification. recommendation initial definition browser compatibility the compatibility table on this page is generated from structured data. if you'd like to contribute to the data, please check out https://github.com/md...
page-mod - Archive of obsolete content
pagemod.pagemod({ include: "*", contentscriptfile: "./my-script.js" }); to attach multiple scripts, pass an array of urls. var data = require("sdk/self").data; var pagemod = require("sdk/page-mod"); pagemod.pagemod({ include: "*", contentscriptfile: [data.url("jquery.min.js"), data.url("my-script.js")] }); content scripts specified using this option are loaded before those specified by the contentscript option. name: contentscript type: string,array this option specifies one or more content scripts to attach to targeted documents. each script is supplied directly as a single string: var pagemod = require("sdk/page-mod"); pagemod.pagemod({ include: "*", contentscript: 'window.alert("matched!");' }); to attach multiple scripts, ...
...g by default, content scripts are attached after all the content (dom, js, css, images) for the document has been loaded, at the time the window.onload event fires. using this option you can customize this behavior. ...
...rg", contentstylefile: data.url("style.css") }); from firefox 34, you can use "./style.css" as an alias for the resource:// url pointing to the stylesheet in your "data" directory. so you can rewrite the code above like this: var pagemod = require("sdk/page-mod"); pagemod.pagemod({ include: "*.org", contentstylefile: "./style.css" }); content styles specified by this option are loaded before those specified by the contentstyle option. in earlier versions of this module, you couldn't use relative urls in stylesheets loaded in this way, and you had to use a workaround. in current versions this has been fixed, and the workaround is no longer needed. name:contentstyle type: string,array use this option to load one or more stylesheet rules into the targeted documents. each ...
page-worker - Archive of obsolete content
trings. these define the documents to which the page-worker's content worker applies. at least one match pattern must be supplied. see the match-pattern module for a detailed description of match pattern syntax. contentscriptfile string,array a local file url or an array of local file urls of content scripts to load. content scripts specified by this option are loaded before those specified by the contentscript option. see working with content 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 ...
...ining 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. this may take one of the following values: "start": load content scripts immediately after the document element for the page is inserted into the dom, but before the dom content itself has been loaded "ready": load content scripts once dom content has been loaded, corresponding to the domcontentloaded event "end": load content scripts once all the content (dom, js, css, images) for the page has been loaded, at the time the window.onload event fires this property is optional and defaults to "end". contentscriptoptions ob...
...entscriptfile a local file url or an array of local file urls of content scripts to load. contentscript a string or an array of strings containing the texts of content scripts to load. contentscriptwhen when to load the content scripts. this may have one of the following values: "start": load content scripts immediately after the document element for the page is inserted into the dom, but before the dom content itself has been loaded "ready": load content scripts once dom content has been loaded, corresponding to the domcontentloaded event "end": load content scripts once all the content (dom, js, css, images) for the page has been loaded, at the time the window.onload event fires contentscriptoptions read-only value exposed to content scripts under self.options property. any kind ...
/loader - Archive of obsolete content
loader module exposes a main() function that can be used to load a main module. ...
...r'); let loader = loader(options); let program = main(loader, './main'); a module can find out whether it was loaded as main: if (require.main === module) main(); it is possible to load other modules before a main one, but it's inherently harder to do. that's because every module except main has a requirer, based on which resolution and authority decisions are made. ...
...box, 'resource://path/to/script.js') // evaluate `code` as if it was from `foo/bar.js`: evaluate(sandbox, 'foo/bar.js', { source: code, version: '1.7' // you could also use other options described above. }) require() as already mentioned in loading modules it's common to start execution by loading a main module. but sometimes you may want to prepare the environment using existing modules before doing that. in such cases you can create a requirer module instance and a version of require exposed to it with this function: let requirer = module(requirerid, requireruri); let require = require(loader, requirer); let boostrap = require(bootstrapid); resolveuri() this function is used by the loader to resolve module uri from an id using a mapping array generated from the loader's paths optio...
content/symbiont - Archive of obsolete content
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. this may take one of the following values: "start": load content scripts immediately after the document element for the page is inserted into the dom, but before the dom content itself has been loaded "ready": load content scripts once dom content has been loaded, corresponding to the domcontentloaded event "end": load content scripts once all the content (dom, js, css, images) for the page has been loaded, at the time the window.onload event fires this property is optional and defaults to "end". contentscriptoptions ob...
...lts 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 properties that are listed below: properties contentscriptfile the 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. this may have one of the following values: "start": load content scripts immediately after the document element for the page is in...
...ontentscript 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. this may have one of the following values: "start": load content scripts immediately after the document element for the page is inserted into the dom, but before the dom content itself has been loaded "ready": load content scripts once dom content has been loaded, corresponding to the domcontentloaded event "end": load content scripts once all the content (dom, js, css, images) for the page has been loaded, at the time the window.onload event fires contentscriptoptions read-only value exposed to content scripts under self.options property. any kind ...
Bootstrapped extensions - Archive of obsolete content
for details. in firefox 10 and later the chrome.manifest file located in the root of the add-on's xpi (i.e. a sibling of the install.rdf) is loaded automatically. in firefox 8 and 9 you had to load/unload the manifest manually using nsicomponentmanager.addbootstrappedmanifestlocation() and nsicomponentmanager.removebootstrappedmanifestlocation(). this feature was unavailable in firefox versions before 8. adding user interface manually if you decide to go ahead and try to develop a bootstrapped extension that modifies the application's user interface, here are a few suggestions to get you started. you need to look up the relevant 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...
...wn, and objects disposed of. void shutdown( data, reason ); parameters data a bootstrap data structure. reason one of the reason constants, indicating why the extension is being shut down. this will be one of app_shutdown, addon_disable, addon_uninstall, addon_upgrade, or addon_downgrade. install your bootstrap script must include an install() function, which the application calls before the first call to startup() after the extension is installed, upgraded, or downgraded. void install( data, reason ); parameters data a bootstrap data structure. reason one of the reason constants, indicating why the extension is being installed. this will be one of addon_install, addon_upgrade, or addon_downgrade. uninstall this function is called after the last call to shutdown()...
...the first call to startup() after the extension is installed, upgraded, or downgraded. void install( data, reason ); parameters data a bootstrap data structure. reason one of the reason constants, indicating why the extension is being installed. this will be one of addon_install, addon_upgrade, or addon_downgrade. uninstall this function is called after the last call to shutdown() before a particular version of an extension is uninstalled. note: if you open the add-on manager and then click "remove" on an add-on, it will not call uninstall function right away. this is a soft uninstall because of the available "undo" option. if the add-on manager is closed or another event takes place such that the "undo" option becomes unavailable, then the hard uninstall takes place and the uni...
Forms related code snippets - Archive of obsolete content
here are some <form> related code snippets. date picker (before implementing it in a working environment, please read the note about the const statement compatibility) <!doctype html> <html> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8" /> <title>datepicker example - mdn</title> <script type="text/javascript"> /*\ |*| |*| datepicker example mdndeveloper network |*| |*| https://developer.mozilla.org/docs/code_snippets/forms |*| https://developer.mozilla.org/user:fusionchess |*| |*| this snippet is released under the gnu public license, version 3 or later. |*| http://www.gnu.org/licenses/gpl-3.0-standalone.html |*| \*/ (function () { function datepicker (otarget) { const otable = document.createelement("table"), ohrow = document.createelement(...
... this.writedays(); otarget.onclick = function () { if (otable.parentnode) { otable.parentnode.removechild(otable); return; } otable.style.zindex = nzindex++; otable.style.position = "absolute"; otable.style.left = otarget.offsetleft + "px"; otable.style.top = (otarget.offsettop + otarget.offsetheight) + "px"; otarget.parentnode.insertbefore(otable, otarget); }; ainstances.push(this); } datepicker.prototype.writedays = function () { const nendblanks = (this.current.getday() + bzeroismonday * 6) % 7, nend = amonthlengths[this.current.getmonth()] + nendblanks, ntotal = nend + ((7 - nend % 7) % 7); var otd, otr; if (this.otbody) { this.container.removechild(this.otbody); } thi...
... to emulate an editable select through a <fieldset> of radioboxes and textboxes (written in pure css, without javascript), please see this example. autogrowing <textarea> this example shows how to make a textarea really autogrowing during a typing. insert some custom text in a <textarea> this example shows how to insert some html tags or smiles or any custom text in a textarea. image preview before upload the filereader.prototype.readasdataurl() method can be useful, for example, to get a preview of an image before uploading it.[article] this example shows how to use it in this way. note: the filereader() constructor was not supported by internet explorer for versions before 10. for a full compatibility code you can see our crossbrowser possible solution for image preview. filter the dig...
Extension Versioning, Update and Compatibility - Archive of obsolete content
the toolkit version format supports the firefox version format but allows greater flexibility. how applications determine compatibility when installing add-ons applications look at the targetapplication entries in the add-on's install.rdf. ...
...on that match the toolkit version of the running application. this allows you to say that your add-on will install into any toolkit based application. overriding compatibility checking for testing purposes you can tell the application to somewhat ignore compatibility checks when installing add-ons. simply create the boolean preference extensions.checkcompatibility and set it to false. note: before firefox 1.5 the preference app.extensions.version could be used to override the version that the application believed itself to be to allow normally incompatible extensions to install. choosing minversion and maxversion minversion and maxversion should specify the range of versions of the application you have tested with. in particular you should never specify a maxversion that is larger than t...
...lar http, gecko 1.9 based applications will require that you digitally sign the update manifest to ensure that it's information isn't tampered with between you creating it and applications retrieving it. the mccoy tool should be used to sign the update rdf. the technical details of the signing mechanism are beyond the scope of this document however the basics are as follows: step 1 - done once, before you publish your add-on the target: adding updatekey in install.rdf the add-on author creates a public/private rsa cryptographic key pair. the public part of the key is der encoded and then base 64 encoded and added to the add-on's install.rdf as an updatekey entry. step 2 - done every time you change your "update.rdf" file the target: setting value to signature in update.rdf when the autho...
Making it into a static overlay - Archive of obsolete content
taller packages are called xpis (pronounced "zippies"), which stands for cross-platform installer. the packages are just standard zip archives of the files to be installed along with a javascript script that performs the installation and some rdf files that describe the components being installed for the chrome registry. because our extension modifies an existing file in the mozilla distribution, before we package it up we need to separate the modifications into a different file and add them back in at run time via a dynamic xul overlay. a xul overlay is a xul file containing elements to be inserted into another xul file when the other xul file is rendered into an application interface. static overlays are added to a xul file via a reference at the top of the file (much like stylesheets and java...
...its next line is the stylesheet reference we previously added to navigator.xul. after that is a xul overlay element. this element is the top-level element in a xul overlay file and serves to ide...
...bar element in navigator.xul. when navigator.xul is rendering into the browser's application interface, this causes any attributes or child elements of the statusbar element in the overlay file to be added to the interface's dom and thus show up in the interface as if they were defined on the same element in navigator.xul. note that we've added a new attribute to the statusbarpanel element: insertbefore. this attribute identifies another statusbarpanel element within statusbar before which our element should appear. thus it allows us to define the exact position of our element relative to the other statusbarpanel elements within statusbar. if insertbefore is omitted, the element will be added as the last child of statusbar, usually before the resizer grippy. we could instead have used an inserta...
Style System Overview - Archive of obsolete content
ch initializes the correct one of the data structs on the stack (the structs used by nscssdeclaration) style data computation get*data calls nsrulenode::walkruletree, which walks from the style context's rule node towards the root rule node. to fill in the data, we call nsistylerule::mapruleinfointo on the rules. mapruleinfointo implementations must check that the property is not filled in before filling it in. walkruletree stops walking up when it finds either a none bit, a cached struct, a dependent bit, or all the properties have been filled in. walkruletree also remembers the first rule that contributed non-empty data. style data computation after walkruletree stops walking up, it calls nsrulenode::compute*data to turn the specified values into the mostly-computed style data in...
...ule tree that we can just copy and add to. if the computation in compute*data used any data from the parent style context, we cache the struct on the style context. otherwise, we cache the struct in the rule tree, on the first rule node that contributed any data, and mark dependent bits on the path up to that rule node. managing style contexts style contexts must (in most cases) be created before frames are constructed, to determine what frame to create. parent style context determines inheritance; it should always be the content parent. [design flaw in frame/sc relationship] three functions for creating style contexts on nsistyleset, wrapped by similarly named ones on nsiprescontext: resolvestylecontextfor: for elements. resolvepseudostylecontextfor: for pseudo-elements (:firs...
... constructed, to determine what frame to create. parent style context determines inheritance; it should always be the content parent. [design flaw in frame/sc relationship] three functions for creating style contexts on nsistyleset, wrapped by similarly named ones on nsiprescontext: resolvestylecontextfor: for elements. resolvepseudostylecontextfor: for pseudo-elements (:first-letter, :before, etc.) resolvestylecontextfornonelement: skips rule matching and uses root rule node (text frame optimization) managing style contexts style context resolving functions will walk the rule processors in stylesetimpl::filerules, find the correct rule node, and find a current child of the parent (“sibling sharing”) or create a new child. style context doesn't hold pointer to conten...
JavaScript Client API - Archive of obsolete content
s non-confusing (by non-confusing, we mean that people should always know with whom they are dealing and where the information or software they are downloading came from). you may not imply, either directly or by omission, that your third party client is produced or endorsed by mozilla. by providing access to the firefox sync apis, mozilla is not granting you a license to any of our trademarks. before starting before you start learning the javascript api, you should spend some time on http://docs.services.mozilla.com/ reading about how the sync service operates. this will help fundamental understanding significantly. api location the sync javascript client api is defined in files in the services/sync/ directory of mozilla-central or similar repository. terminology syncengine the main s...
...box (history, bookmarks, etc). it is possible for other components, including 3rd party extensions, to supplement the set of engines and synchronize their own data. a word of warning: the javascript client api is still a young component and is continuing to evolve. therefore, developers outside of the sync core should know that their code could require significant refactoring in future releases. before developing against the javascript api, it is recommended to speak to developers of the api. see https://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 ...
...arated list of engine names). you can also set up a component that registers a weave:service:ready observer and at that time, imports main.js as well as your engine. also, for me, doing weave.engines.register(fooengine) worked better then doing weave.fooengine = fooengine. reason for this is, weave will iterate through the registerengines preference and try to instantiate each engine it has there before you the line mentioned above ever has a chance to execute.this means the constructor to your engine is not ready when weave tries to instantiate it. testing and debugging your engine set observers in the tracker to tell when your datatype changes, after which the score needs to be set. you can also add api's to the engine, get a handle of the engine by going weave.engines.get("foo") and call it...
Simple Storage - Archive of obsolete content
), although the data comes loaded automatically. don't abuse these methods, since they cause firefox -- all of firefox -- to drop what it's doing to make a trip to the disk. if you call them too often, firefox may become unresponsive for some of your users. unless you are doing something strange, let jetpack flush your data for you. the namespace currently lives in the future and must be imported before it is used: jetpack.future.import("storage.simple"); methods sync()as described above, the jetpack.storage.simple object is automatically written to disk, but a feature may force flush by calling jetpack.storage.simple.sync(). don't abuse this method. open()as described above, the jetpack.storage.simple object is automatically populated when a feature is loaded, but a feature may force the objec...
...l add a notes menu with// a submenu, which lists all the notes. ...
...length > 0 ? ...
Clipboard Test - Archive of obsolete content
features can get and set the ...
...display:inline-block; width:300px; vertical-align:top;margin-right:30px} .method>.params>.param>.type{display:inline-block; width:100px; vertical-align:top;font-weight:bold;} .method>.params>.param>.type:before{content: "type "; color: #888; font-weight:normal;} .method>.params>.param>.default{display:inline-block; width:100px; vertical-align:top;font-weight:bold;} .method>.params>.param>.default:before{content: "default "; color: #888;font-weight:normal;} ]]></style> clipboard jetpack's clipboard support api provides a standardized way for features to access the clipboard. features can get and set the clipboard in various flavors of data type. the namespace associated with this api is jetpack.clipboard which provides both read and write access to the clipboard. the api is fairly straightforward...
...hello world");// in other clipboard get(flavor string)returns data to jetpack from the clipboard. if flavor is provided, the data is returned in that format. flavorreturns data to jetpack from the clipboard. if flavor is provided, the data is returned in that format. string here's an example of how to use the method to get the data on the clipboard. remember to import clipboard from the future before calling it. jetpack.import.future("clipboard");var mycontent = "<i>this is some italic text</i>";jetpack.clipboard.set( mycontent, "html" ); getcurrentflavors()returns an array of available jetpack clipboard flavors, for the current system clipboard state. jetpack.import.future("clipboard");var mycontent = "<i>this is some italic text</i>";jetpack.clipboard.set( mycontent, "html" );var flavs = je...
Simple Storage - Archive of obsolete content
), although the data comes loaded automatically. don't abuse these methods, since they cause firefox -- all of firefox -- to drop what it's doing to make a trip to the disk. if you call them too often, firefox may become unresponsive for some of your users. unless you are doing something strange, let jetpack flush your data for you. the namespace currently lives in the future and must be imported before it is used: jetpack.future.import("storage.simple"); methods sync()as described above, the jetpack.storage.simple object is automatically written to disk, but a feature may force flush by calling jetpack.storage.simple.sync(). don't abuse this method. open()as described above, the jetpack.storage.simple object is automatically populated when a feature is loaded, but a feature may force the objec...
...s menu with // a submenu, which lists all the notes. if there are no notes, we'll show a // disabled "(empty)" menuitem. ...
... ? notes : [{ label: "(empty)", disabled: true }]) }); } // modify the page's context menu by sneaking in before it's shown. if there's // a selection, add a note menuitem that makes a new note. otherwise, don't // modify the menu at all. we'll limit the number of notes to 20. old notes // will be forgotten. :( jetpack.menu.context.page.beforeshow = function (menu) { menu.reset(); if (jetpack.selection.text) menu.add({ label: "note", command: function () { notes.unshift(jetpack.selection.text); if (notes.length > 20) notes.pop(); updatejetpackmenu(); } }); }; // initialize the jetpack menu with the current notes. updatejetpackmenu(); see also settings jep 11 ...
Space Manager High Level Design - Archive of obsolete content
created the blockreflowstate's previous space manager is saved off. the new space manager instance is associated with the blockreflowstate. after the block frame's reflow has completed, the old space manager instance is re-associated with the blockreflowstate the new space manager is destroyed. if the blockreflowstate already had a space manager instance associated with it, it is stored off before being replaced, and the returned to the blockreflowstate instance after the new one has been destroyed. thus, space managers are effectively 'nested' during reflow, with each new block introducing its own space manager. use case 2: float is added to the space manager after a space manager is created for a block context's reflow chain, a floated block may be added to it. this happens in the met...
...should be private (compiles fine) nsblockframe::paint is mucking...
...should be private (compiles fine) nsblockframe::paint is mucking with nsblockbanddata in and #if 0 block - remove that and th...
Elements - Archive of obsolete content
to point to a specific binding id within a binding document. note that content cannot be inherited, only behavior. display - this attribute specifies how the tag is displayed. by setting this attribute, you can have an element have the layout and display characteristics of an existing element. for example, use the value 'xul:button' to create an element that is displayed like a button. the part before the colon is a namespace prefix so you must declare the xul namespace as well. not all tags have a unique display type. the following xul display types may be used: browser, button, checkbox, description, editor, grippy, iframe, image, label, menu, menuitem, menubar, progressmeter, radio, resizer, scrollbar, scrollbox, spacer, splitter, titlebar, treechildren and treecol. you may also use a numbe...
...been accessed. if a proto is inserted into the proto chain after binding instantiation, doing so may affect field values (this wasn't the case in prior versions of firefox). at binding attachment time, <field name="parentnode">this.parentnode</field> is undefined instead of the value of parentnode. a field no longer changes the value of a property set on the object itself (rather than a proto) before binding attachment. property <!entity % property-content "(getter?,setter?)"> <!element property %property-content;> <!attlist property id id #implied name cdata #required readonly (true|false) #implied onget cdata #implied onset cdata #implied > the proper...
...ccel - the platform's primary accelerator key. it is left up to the user agent to decide which modifier key represents the primary key. (it's the control key on windows and meta on mac.) accesskey - the platform's primary shortcut mnemonic key should be used (the alt key on windows and linux, has no effect on mac). any - this causes the filter to ignore the state of any modifiers that occur before the any keword. for example: key="x" modifiers="control shift any" - the handler will match whether or not the control and/or shift keys are pressed. this will match control-x, shift-x, control-shift-x, and x with no modifiers. it will not match any other combinations, such as alt-x or control-altx. key="x" modifiers="control any shift" - the handler will match if the shift key ...
Windows Install - Archive of obsolete content
windows install example this example shows the installation of a xpi in which user profile information is contained. note the disk space verification, the editing of the windows registry, the writing to the installation log, and the error checking before either performinstall or cancelinstall is called. // this function verifies disk space in kilobytes function verifydiskspace(dirpath, spacerequired) { var spaceavailable; // get the available disk space on the given path spaceavailable = filegetdiskspaceavailable(dirpath); // convert the available disk space into kilobytes spaceavailable = parseint(spaceavailable / 1024); // do the verification if(spaceavailable < spacerequired) { logcomment("insufficient disk space: " + dirpath); logcomment(" required : " + spac...
... var subkey; // the name of the subkey you are poking around in var valname; // the name of the value you want to look at var value; // the data in the value you want to look at. var winreg = getwinregistry() ; if(winreg != null) { // here, we get the current version. winreg.set...
... logcomment(" required : " + spacerequired + " k"); logcomment(" available: " + spaceavailable + " k"); return(false); } return(true); } function updatewinreg4ren8dot3() { var fprogram = getfolder("program"); var ftemp = getfolder("temporary"); //notes: // can't use a double backslash before subkey // - windows already puts it in. // subkeys have to exist before values can be put in. var subkey; // the name of the subkey you are poking around in var valname; // the name of the value you want to look at var value; // the data in the value you want to look at. var winreg = getwinregistry() ; if(winreg != null) { // here, we get the current version. winreg.setrootkey(winreg.hkey_current_user) ;// current_user subkey = "soft...
collapse - Archive of obsolete content
« xul reference home collapse type: one of the values below determines which side of the splitter is collapsed when its grippy is clicked. if this attribute is not specified, the splitter will not cause a collapse. you should put a grippy element inside the splitter when it is used for collapsing. none no collapsing occurs. ...
...xul reference home collapse type: one of the values below determines which side of the splitter is collapsed when its grippy is clicked. if this attribute is not specified, the splitter will not cause a collapse. you should put a grippy element inside the splitter when it is used for collapsing. none no collapsing occurs. ...
...n 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. both either the element immediately before the splitter, or the element immediately after the splitter can be collapsed, if the size of that element would fall below the minimum size due to the position of the splitter. ...
timeout - Archive of obsolete content
there is no default. ...
...there is no default. ...
...there is no default. ...
XUL Events - Archive of obsolete content
popup after it has been hidden. attribute: onpopuphidden popuphiding this event is sent to a popup when it is about to be hidden. attribute: onpopuphiding popupshowing this event is sent to a popup just before it is popped open. this handler is usually used to dynamically set the contents when the user requests to display it. returning false from this event handler prevents the popup from appearing. attribute: onpopupshowing popupshown this event is sent to a popup after it has been opened, much like the o...
... event is sent when a checkbox is checked or unchecked, either by the user or a script. normally, you would use the command event to listen to checkbox changes, however, the command event is only sent when the user modifies the value, while the checkboxstatechange event is also sent when a script modifies the checked property of a checkbox. for user changes, the checkboxstatechange event is sent before the command event. the checkboxstatechange event does not bubble. radiostatechange this event is sent when a radio button is selected, either by the user or a script. normally, you would use the command event to listen to radio button selection changes, however, the command event is only sent when the user chan...
... this event is sent when a radio button is selected, either by the user or a script. normally, you would use the command event to listen to radio button selection changes, however, the command event is only sent when the user changes the selected radio button, while the radiostatechange event is also sent when a script modifies the selection. for user changes, the radiostatechange event is sent before the command event. the radiostatechange event bubbles so you can also attach the event handler to the enclosing radiogroup. ...
Attribute Substitution - Archive of obsolete content
« previousnext » so far, attribute replacement in an action body has been used to replace an entire attribute with the value of a variable. however, you may also replace only part of attribute's value, or use multiple variables in one attribute. for instance, to include a prefix before a variable value, you can use: <label value="my name is ?name"/> the effect will be that the ?name part of the attribute will be replaced by the value of the variable ?name. for instance, if the value of ?name is 'jake', then the attribute value will be 'my name is jake'. you can include multiple variables in one attribute if desired: <label value="my name is ?name and my age is ?age"/> this technique will work for any variable replacement in the action body, except for the uri attribute since t...
...de value="?description"/></description> the resulting generated content might be: <description>view from the top of the tower looking east of the doges palace</description> note that the textnode has been replaced with the substituted value attribute. note that in firefox 2 and earlier, a bug can make this appear to not work at times. recall that the template builder doesn't load the datasource before processing a template. as the datasource loads, the query and rules are examined with the new data as it arrives. this causes rules to create matches as the data loads. however, variables determined from a binding are evaluated using a much simpler process. the bug is that this code path for bindings doesn't handle the textnode element properly. thus, if you use a variable set in a binding, you m...
...ource loads, the query and rules are examined with the new data as it arrives. this causes rules to create matches as the data loads. however, variables determined from a binding are evaluated using a much simpler process. the bug is that this code path for bindings doesn't handle the textnode element properly. thus, if you use a variable set in a binding, you must ensure the datasource is loaded before the template is built, or just rebuild the template. another possibilty is to rearrange the rdf such that the values, in this example, the descriptions, are specified before the containers. this issue is fixed in firefox 3 (mozilla 1.9) and later. « previousnext » ...
Multiple Queries - Archive of obsolete content
. how multiple queries are processed we already know that a query generates a set of results. there's no magic to the way in which the template builder processes multiple queries. it just takes the results generated from the first query, adds the results for the second query, adds the results for the third query, and so on. ...
...) so four possible results are available, one from the first query and three from the second. however, the example shows that only content for three results are generated. what happened to the fourth result? this is where the useful aspect of multiple queries comes in. note that two of the results above are actually for the same photo (canal.jpg). the template builder removes any duplicate items before generating content. it does this by only allowing the match for the earliest query. that is, the canal.jpg generated by the second query is removed, since an earlier query (the first query) already generated a match for that result. one important distinction is that the determination of duplicates is only based on the member variable, in this case the ?photo variable. it doesn't matter whether ot...
...only based on the member variable, in this case the ?photo variable. it doesn't matter whether other variables are the same or not. if you look at the example again, you might notice that the canal photo that matches the first query has appeared in-between the other two photos, even though those photos are generated from the second query. the builder hasn't put all the matches for the first query before the matches for the second query. in fact, the order is the same as the examples that only use one query. compare the multiple query example with an earlier example that used only a single query. the photos have appeared in the same order in both cases. this is because the builder notices that the photos are in an rdf seq in the datasource and arranges them in the order they appear in the seq. th...
Accesskey display rules - Archive of obsolete content
label has two or more characters which are same as its accesskey, the first character of them will be underlined. if a label doesn't have the character, xul elements append the accesskey character with parentheses. e.g., when an accesskey of "open" is 'a', the generated label will be "open (a)". however, if the last character of the label is an ellipsis or a colon, the accesskey text is inserted before them. i.e., when an accesskey of "open…" is 'a', the generated label will be "open (a)…". and also when an accesskey of "your name:" is 'b', the generated label will be "your name (b):". this document calls the appended text "accesskey text". always appends accesskey text the basic rules are enough for western locales. however, in some locales, e.g., japanese localized build, its most ui lab...
...accesskey text always. if the value is "true" (string), the accesskey text will be appended always. don't change the pref value from your xul applications. and also note that there are no spaces between the original labels and accesskey text in the above japanese example. because typically, japanese language doesn't use spaces as word separator. this is controled by "intl.menuitems.insertseparatorbeforeaccesskeys" pref value. if the value is "true" (string), a spece will be inserted before accesskey text. don't change the pref value from your xul applications too. don't include accesskey text in labels xul applications should use dtd for localizable ui resource. at that time, accesskeys are specified by independent entity from their label. be aware, this is very important thing. when you cannot...
...キャンセル(&c)". this label will be displayed as "キャンセル(c)(c)" on the localized build. so, "(c)" will be doubled. for this issue, we recommend the following format if you use .properties: <command-name>.label=cancel <command-name>.accesskey=c note that apis of nsipromptservice are using the bad way. because the apis are already frozen. therefore, xul toolkit removes accesskey text before setting the label to the buttons. however, xul application developers should not make same mistake. ...
More Event Handlers - Archive of obsolete content
</vbox> stop event propagation once you handle an event, regardless of where in the propagation the event is, you will likely want to stop the event from being sent to further elements, essentially stopping the capturing or bubbling phases from continuing. depending on how you attach the event listener to an element, there are different ways of doing this. recall that the capturing phase occurs before the bubbling phase, so any capturing listeners will trigger before any bubbling listeners. if a capturing event stops the event propagation, none of the later capturing listeners, nor any of the bubbling listeners will ever receive notification about the events. to manually stop event propagation, call the event object's stoppropagation method, as in the following example. example 2 : source view...
...if this call was removed, both listeners would be called and both alerts would appear. prevent default action if no event handlers have been registered for an event, then after completing the capturing and bubbling phases, the element will handle the event in a default way. what will happen depends on the event and the type of element. for example, the 'popupshowing' event is sent to a popup just before it is displayed. the default action is to display the popup. if the default action is prevented, the popup will not be displayed. the default action can be prevented with the event object's preventdefault method, as in the example below. example 3 : source view <button label="types" type="menu"> <menupopup onpopupshowing="event.preventdefault();"> <menuitem label="glass"/> <menuitem lab...
...the box object in a later section, but it holds information pertaining to how the element is displayed, including the x and y position of the element. in this example code, these coordinates are subtracted from the event coordinates to get the event position relative to the element. load events the load event is sent to the document (the window tag) once the xul file has finished loading and just before the content is displayed. this event is commonly used to initialize fields and perform other tasks that need to be done before the user can use the window. you should use a load event to do these kinds of things as opposed to adding a script at the top level outside of a function. this is because the xul elements may not have loaded or fully initialized yet, so some things may not work as expecte...
Popup Menus - Archive of obsolete content
_start the popup appears below the element with the left edges of the element and the popup window aligned. if the popup window is larger than the element, is extends to the right. this is the value used for the drop-down menus associated with the browser's back and forward buttons. after_end the popup appears below the element with the right edges of the element and the popup window aligned. ...
...popup window is larger than the element, is extends to the right. this is the value used for the drop-down menus associated with the browser's back and forward buttons. after_end the popup appears below the element with the right edges of the element and the popup window aligned. before_start the popup appears above the element with the left edges of the element and the popup window aligned. before_end the popup appears above the element with the right edges of the element and the popup window aligned. end_after the popup appears to the right of the element with the bottom edges of the element and the popup window aligned. end_before the popup appears to the right of the element with the top edges of the element and the popup window aligned. start_after the popup appears to the left ...
... overlap the popup appears on top of the element. ...
Using the Editor from XUL - Archive of obsolete content
his to poke the ui (e.g. for command state maintenance, starting and stopping the throbber etc.). the contentwindow (another settable attribute on nsieditorshell) points to the xul element which is to become editable. note: since we already know this when we have an <editor></editor> tag, we should remove the need to call this. editorstartup() does some other minor bits of setup before finally kicking off the url load, which the most important part here. when the xul was parsed, the src attribute on the content frame was set to about:blank (our default 'blank page' url). we can't set that before xul parsing, so we have to force a load of the page we now want to edit. we get the url to load from the args element, then kick off the load: var url = document.getelementbyid("a...
... user if they want to save the document, throw away their changes, or cancel. note that if they cancel, the close operation is aborted. the user clicks the close widget in their os/window manager. in this case, the onclose method on the <window> element is called. the user chooses 'close' from the file menu, uses the key shortcut, or quits the application, causing all windows to be closed. before each window is closed, javascript code in globaloverlay.js tries to call a trytoclose method on each window. in editor.js, we set this to call editorcanclose(). if the user chooses to save the document, or throw away their changes, then the window is closed. when the last reference to the nseditorshell goes away (as a result of nseditorboxobject releasing its reference) it releases the owning r...
...n off selection and layout updating (to avoid flicker), and the maintenance of a placeholder transaction. this placeholder transaction enables us to batch typing events together, so that an undo undoes the whole series of keystrokes. another stack-based class, nsautorules, ensures that text insertion is wrapped with calls to nshtmleditor::startoperation() / endoperation(). these functions call beforeedit() and afteredit() on the current typing rules. now, we initialize a nstextrulesinfo with the information about the string being inserted, and call willdoaction() on the current editing rules. because the implementation of inserting text differs between the different rules (plain text vs. html, for example), it is handled entirely by the rules code, in the willdoaction()call. in composer...
XUL element attributes - Archive of obsolete content
unique identifier so that you can identify the element with. you can use this as a parameter to getelementbyid() and other dom functions and to reference the element in style sheets. insertafter type: id when an element is in an overlay, the insertafter attribute specifies the id of the element in the base window that the element should appear after. this attribute overrides the insertbefore attribute. this value may be a comma-separated list of ids, which are scanned and the first one found in the window is used. insertbefore type: id when an element is in an overlay, the insertbefore attribute specifies the id of the element in the base window that the element should appear before. this value may be a comma-separated list of ids, which are scanned and the first one found i...
...in mozilla, persistent attributes are stored in the per-profile file xulstore.json. persistence can also be stored using the document.persist function. in order for persistence to work, the element must also have an id. persistence will not remember the absence of an attribute, so for boolean attributes like checked where absence means false, you will need to explicitly set the attribute to false before the window closes (bug 15232). popup type: id should be set to the value of the id of the popup element that should appear when the user clicks on the element. position type: string (representing an integer) when an element is in an overlay, the position is an index where the child is inserted. the position is one-based, so use a value of 1 to place the element at the beginnin...
...pe: id should be set to the value of the id of the popup element that should appear when the user clicks on the element. position type: string (representing an integer) when an element is in an overlay, the position is an index where the child is inserted. the position is one-based, so use a value of 1 to place the element at the beginning. this attribute is ignored if either an insertbefore or insertafter attribute matches an element. preference-editable mozilla 1.8 type: boolean if true, the element may be used as one that modifies a preference in a prefwindow. the preference attribute may be used to connect to a preference element. this is useful for custom elements implemented in xbl. the element should fire change, command, or input event when the value is changed so t...
XUL Event Propagation - Archive of obsolete content
when the given event is "heard". the availability of event listeners is also somewhat pre-determined, though xul provide generalized event listeners (i.e., oncommand event listeners) for most of the elements in the widget hierarchy. event handlers are written by you, the developer of the interface. very often, the event raised by the element is heard by the element itself and handled right there before it bubbles up any higher. this is the case in the example code in the diagram, where the onclick event listener for the button element handles the click event 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, e...
...the case in the example code in the diagram, where the onclick event listener for the button element handles the click event 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. the combination of basic these two basic event flow mechanisms, event bubbling and event capturing, mean that events raised in the interface can be caught anywhere above the element that raised the event. this flexibility in the xul event model is the focus of this article. the widget hierarchy consider the following xul file: ...
...... the event handler in the menu finds out which menuitem was actually clicked and takes different actions accordingly. event capturing event capturing is the complement of event bubbling. when you register an event listener on an ancestor of the event target (i.e. any node above the event-raising element in the node hierarchy), you can use event capturing to handle the event in the ancestor before it is heard in the target itself or any of the intervening nodes. in the diagram above, the alert dialog invoked by the menuitem itself is not displayed, since the root window element has used event capture to handle the event itself. in another example, an onload event handler for a xul window can register a box element to capture all the click events that are raised from its child elements: ...
iframe - Archive of obsolete content
ontent type. this boundary has a number of special effects, such as making window.top == window (unless the browser is added to a chrome document), and preventing documents from inheriting the principal of the parent document. the type attribute on all frames in content documents is ignored; subdocuments of content documents are always content documents. warning: the type attribute must be set before the element is inserted into the document. content a browser for content. the content that is loaded inside the browser is not allowed to access the chrome above it. content-primary the primary browser for content. the content that is loaded inside the browser is not allowed to access the chrome above it. for instance, in a web browser, this would be the element that displays the we...
...n iframe as transparent.transparentthis results in the iframe's background being transparent. ...
...aredocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), removeattributenode(), removeattributens(), removechild(), removeeventlistener(), replacechild(), setattribute(), setattributenode(), setattributenodens(), setattributens(), setuserdata related nsiaccessibleprovider ...
progressmeter - Archive of obsolete content
erence home [ examples | attributes | properties | methods | related ] a meter which can be used to display the progress of a lengthy operation. it is drawn as a bar that is filled as the operation completes. in addition, an indeterminate progressmeter may be created by setting the mode attribute to undetermined. this is used when the length of time to complete an operation is not known beforehand. more information is available in the xul tutorial. attributes max, mode, value properties accessibletype, max, mode, value examples <progressmeter mode="determined" value="82"/> <progressmeter mode="undetermined"/> <!-- switching modes while the mouse is over a button --> <progressmeter mode="determined" id="myprogress"/> <button label="example" onmouseover="setloading(true)...
...mum 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. ...
...aredocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), removeattributenode(), removeattributens(), removechild(), removeeventlistener(), replacechild(), setattribute(), setattributenode(), setattributenodens(), setattributens(), setuserdata related interfaces nsiaccessibleprov...
tab - Archive of obsolete content
Archive › Mozilla › XUL › tab
« xul reference home [ examples | attributes | properties | methods | related ] a single tab which should be placed inside a tabs element. the user may click a tab to bring the associated page of the tabbox to the front. more information is available in the xul tutorial. attributes accesskey, afterselected, beforeselected, command, crop, disabled, first-tab, image, label, last-tab, linkedpanel, oncommand, pending, pinned, selected, tabindex, unread, validate, value properties accesskey, accessibletype, command, control, crop, disabled, image, label, linkedpanel, selected, tabindex, value examples (example needed) 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...
...ld be one of the characters that appears in the label attribute for the element. afterselected type: boolean this is set to true if the tab is immediately after the currently selected tab. this is 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. beforeselected type: boolean this is set to true if the tab is immediately before the currently selected tab. this is set automatically set when needed and you shouldn't adjust it manually. this is primarily useful for themes so that they can adjust the appearance of the area around the selected tab. crop type: one of the values below if the label of the element is too big to...
...aredocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), removeattributenode(), removeattributens(), removechild(), removeeventlistener(), replacechild(), setattribute(), setattributenode(), setattributenodens(), setattributens(), setuserdata notes note: prior to gecko 1.9, disabl...
Getting started with XULRunner - Archive of obsolete content
nifest in the application root which will include the the manifest in our chrome root. here is the application root chrome.manifest: manifest chrome/chrome.manifest step 6: set up preferences the prefs.js file tells xulrunner the name of the xul file to use as the main window. ...
...to execute this: c:\path\to\xulrunner.exe application.ini of course, if you opted to install xulrunner then you could simply do ​%programfiles%\xulrunner.exe application.ini or on 64 bit systems ​%programfiles(x86)%\xulrunner.exe application.ini note: you can also install your application when you're finished debugging it. see xul application packaging for details. mac on the mac, before you can run a xulrunner application with everything intact, you must install it using the --install-app xulrunner commandline flag. installing the application creates an os x application bundle: /library/frameworks/xul.framework/xulrunner-bin --install-app /<path>/<to>/myapp.zip once installed, you can run the application: /library/frameworks/xul.framework/xulrunner-bin "/applications/finkl...
...firefox browser that normally starts. this is similar to starting a xul app using xulrunner. see using firefox to run xulrunner applications. this does not work if firefox itself was installed as a xul app - you need to use the installed xulrunner directly. further reading: there are many things you can do with xulrunner (who would have thought that? typical mozilla writing style at play here). before you get too far into things you might want to read the xulrunner tips article. also, throughout this tutorial you've been introduced to various bits of the toolkit api and it may help you to get familiar with it. once you've got an application that's ready for the world you'll love our article titled deploying xulrunner. for now, click the "next" link to learn about windows and menus in xulrunne...
Archived Mozilla and build documentation - Archive of obsolete content
t explorer to mozilla when netscape started the mozilla browser, it made the conscious decision to support w3c standards. as a result, mozilla is not fully backwards-compatible with netscape navigator 4.x and microsoft internet explorer legacy code; for example, mozilla does not support <layer> as i will discuss later. browsers, like internet explorer 4, that were built before the conception of w3c standards inherited many quirks. in this article, i will describe mozilla's quirks mode, which provides strong backwards html compatibility with internet explorer and other legacy browsers. monitoring downloads firefox 3 makes it easier than ever to monitor the status of downloads. although it was possible to do so in previous vers...
...purposes: table cellmap - border collapse this document describes the additional information that is stored for border collapse tables in the cellmap. table layout regression tests changes in layout, parser and content code can have unintended side effects, also known as regressions. it is good style to check for these unwanted regressions and fixing them before checkin rather than causing bugzilla avalanches. table layout strategy the table layout algorithm is based on two w3c recommendations: 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 fixe...
... using addresses of stack variables with nspr threads on win16 this is a cautionary note that may be old information for some of you. however, since it affects the portability of code, it was deemed prudent to include a short memo describing the issue. when working with mozilla, you tend to accumulate patches which need to be reviewed, super-reviewed, and/or approved before they can be committed to the trunk. when you have only a few uncommitted patches, you can get by using cvs diff, and just editing the output to remove other patches before submitting. however, this approach quickly becomes unscalable, especially when you have different fixes in the same tree. using a distributed versioning system like svk takes out much of the hassle of managing...
Mozilla release FAQ - Archive of obsolete content
elp 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. ...
...to start understanding the issues with this example, you should dig up the rfcs for the relevant protocols, any documents written on the subject, etc. ...
... attempting to save. also, progressive display of the webpage would be completely gone with this idea. for these reasons, this is generally considered a bad idea. i'd like to port mozilla to xxxos. any advice? if you're targeting a relatively recent unix, you probably will have very few problems. otherwise, the more unixlike the target system is, the easier your port will go. ...
Introduction to SSL - Archive of obsolete content
orming it that future messages from the server will be encrypted with the session key. it then sends a separate (encrypted) message indicating that the server portion of the handshake is finished. the ssl handshake is now complete, and the ssl session has begun. the client and the server use the session keys to encrypt and decrypt the data they send to each other and to validate its integrity. before continuing with the session, red hat servers can be configured to check that the client's certificate is present in the user's entry in an ldap directory. this configuration option provides one way of ensuring that the client's certificate has not been revoked. it's important to note that both client and server authentication involve encrypting some piece of data with one key of a public-private...
... to the private key used by the ca to sign the server certificate, the client won't authenticate the server's identity. if the ca's digital signature can be validated, the server treats the user's certificate as a valid "letter of introduction" from that ca and proceeds. at this point, the client has determined that the server certificate is valid. it is the client's responsibility to take step 4 before step 5. does the domain name in the server's certificate match the domain name of the server itself? this step confirms that the server is actually located at the same network address specified by the domain name in the server certificate. although step 4 is not technically part of the ssl protocol, it provides the only protection against a form of security attack known as "man in the middle." c...
...r won't authenticate the user's identity. if the ca's digital signature can be validated, the server treats the user's certificate as a valid "letter of introduction" from that ca and proceeds. at this point, the ssl protocol allows the server to consider the client authenticated and proceed with the connection as described in step 6. red hat servers may optionally be configured to perform step 5 before step 6. is the user's certificate listed in the ldap entry for the user? this optional step provides one way for a system administrator to revoke a user's certificate even if it passes the tests in all the other steps. the red hat certificate system can automatically remove a revoked certificate from the user's entry in the ldap directory. all servers that are set up to perform this step will th...
Examples - Archive of obsolete content
l stylesheet via <code>link</code>. </p> <p> note how the css rules for the background are applied in netscape 7.x, mozilla, opera 7 and internet explorer 5.5+. </p> <p> <a href="http://validator.w3.org/check/referer"><img src="https://udn.realityripple.com/samples/8a/9e64asf935.png" alt="valid xhtml 1.0!" height="31" width="88" /></a> </p> </body> </html> before testing this example by yourself, please read this. back to the article example 5 <!-- this file should have a .xml extension --> <!doctype html public "-//w3c//dtd xhtml 1.0 strict//en" "http://www.w3.org/tr/xhtml1/dtd/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" lang="en-us" xml:lang="en-us"> <head> <title>example 5 - xhtml 1.0 strict as text/xml</title> <meta http...
...ode>. </p> <p> note how the css rules for the background are applied in netscape 7.x, mozilla, opera 7 but that internet explorer can not display the page at all. </p> <p> <a href="http://validator.w3.org/check/referer"><img src="https://udn.realityripple.com/samples/8a/9e64asf935.png" alt="valid xhtml 1.0!" height="31" width="88" /></a> </p> </body> </html> before testing this example by yourself, please read this. back to the article example 6 <!-- this file should have a .xhtml extension --> <!doctype html public "-//w3c//dtd xhtml 1.0 strict//en" "http://www.w3.org/tr/xhtml1/dtd/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" lang="en-us" xml:lang="en-us"> <head> <title>example 6 - xhtml 1.0 strict as application/xhtml+xml</titl...
...ode>. </p> <p> note how the css rules for the background are applied in netscape 7.x, mozilla, opera 7 but that internet explorer can not display the page at all. </p> <p> <a href="http://validator.w3.org/check/referer"><img src="https://udn.realityripple.com/samples/8a/9e64asf935.png" alt="valid xhtml 1.0!" height="31" width="88" /></a> </p> </body> </html> before testing this example by yourself, please read this. back to the article stylesheet /* * if you try to view the results of these examples, * you will need to put a file named style.css with * the following content in the same directory as * the examples. */ body { padding-top: 8em; } html { color: #fff; background: #000 no-repeat fixed;} p {width: 30em; font-weight: bold;} ...
Back to the Server: Server-Side JavaScript On The Rise - Archive of obsolete content
server-side javascript engine. now more than 10 years later, with netscape's technology group having been transformed into the mozilla foundation, server-side javascript is seeing a strong resurgence because of the simplicity it provides to web developers reinvigorated by the fact that today's cpus can process javascript more than 10x faster than the cpus of the mid-90's ever could. and just like before, it's the mozilla team that's at the core of this latest evolution of the web. in fact, the next javascript engine from mozilla, tracemonkey, is poised to boost javascript performance by factors of 20 to 40 times according to brendan eich, mozilla cto and the creator of javascript. in recent developments we also see the advent of other performant engines for javascript such as v8 from google and ...
... form and the out-logger will be used as a log display as each comment is added. the completed user interface is shown in figure 1. figure 1 – the user interface server-side dom processing another powerful concept of jaxer is the ability to access the dom server-side with javascript. this gives you added control to interrogate and manage the document structure before it's pushed to the client. listing 7 contains the code which demonstrates this concept. listing 7 - manipulating the dom server-side <script runat="server"> window.onserverload = function() { document.getelementbyid( "out-logger" ).innerhtml = jaxer.file.read( "dump.txt" ); } </script> the code in listing 7 is executed server-side and takes a...
...is concept. listing 7 - manipulating the dom server-side <script runat="server"> window.onserverload = function() { document.getelementbyid( "out-logger" ).innerhtml = jaxer.file.read( "dump.txt" ); } </script> the code in listing 7 is executed server-side and takes advantage of the onserverload event which ensures that we have a complete dom before trying to access it. this code is simple in that it updates the innerhtml of the logging div with the contents of a text file. the contents of this file are obtained through the file i/o capabilities exposed by jaxer which is what we'll examine next. file i/o jaxer ships with a comprehensive filesystem i/o capability that is very useful. there are numerous methods in thi...
Writing JavaScript for XHTML - Archive of obsolete content
d is gone. the code looks something like this: <script type="text/javascript"> //<!-- window.alert("hello world!"); //--> </script> solution: the cdata trick this problem usually arises, when inline scripts are included in comments. this was common practice in html, to hide the scripts from browsers not capable of js. in the age of xml comments are what they were intended: comments. before processing the file, all comments will be stripped from the document, so enclosing your script in them is like throwing your lunch in a piranha pool. moreover, there's really no point to commenting out your scripts -- no browser written in the last ten years will display your code on the page. the easy solution is to do away with the commenting entirely: <script type="text/javascript"> windo...
...ented in different cases scripts that used getelementsbytagname() with an upper case html name no longer work, and attributes like nodename or tagname return upper case in html and lower case in xhtml. solution: use or convert to lower case for methods like getelementsbytagname(), passing the name in lower case will work in both html and xhtml. for name comparisons, first convert to lower case before doing the comparison (e.g., "el.nodename.tolowercase() === 'html'"). this will ensure that documents in html will compare correctly and will do no harm in xhtml where the names are already lower case. 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 ...
...blem has the same cause as the one above. this method does not exist in xmldocuments anymore. there are reasons why this decision was made, one being that a string of invalid markup will instantly break the whole document. solution: use dom methods many people avoided dom methods because of the typing to create one simple element, when document.write() worked. now you can't do this as easily as before. use dom methods to create all of your elements, attributes and other nodes. this is xml proof, as long as you keep the namespace problem in focus (e.g., there is a document.createelementns method). of course, you can still use strings like in document.write(), but it takes a little more effort. for example: var string = '<div xmlns="http://www.w3.org/999/xhtml"><h1>hello world!</h1></div>'; va...
Building Mozilla XForms - Archive of obsolete content
getting started things to know first: the xforms extension has a dependency on the schema-validation extension, so you need to build both (that's done automatically) mozilla switched from cvs to mercurial 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. the following table gives you an overview of which version you want to build: firefox version gecko/toolkit version source code notes status firefox 2.0 gecko 1.8.1 cvs, branch mozilla_1_8_branc...
...a.org/xforms hg clone http://hg.mozilla.org/schema-validation that's it, you now have everything you need to get started. configure your build: the .mozconfig file mozilla uses a file called .mozconfig in your home directory to store the build configuration. for xforms, you will need to add the following line: ac_add_options --enable-extensions="default,xforms" # if you're using a mozilla source before 2010-11-06 (e.g. an old firefox 3.6 release) use this instead (see bug 601570 for details): ac_add_options --enable-extensions="default,xforms,schema-validation" a complete .mozconfig file for a release build might look like that: . $topsrcdir/browser/config/mozconfig mk_add_options moz_co_project=browser mk_add_options moz_objdir=@topsrcdir@/obj-@config_guess@ #mk_add_options autoconf=autoconf...
...s configuration: . $topsrcdir/browser/config/mozconfig mk_add_options moz_co_project=browser mk_add_options moz_objdir=@topsrcdir@/obj-@config_guess@ ac_add_options --enable-extensions="default,xforms" ac_add_options --enable-debug ac_add_options --disable-optimize ac_add_options --disable-tests building now that you have everything ready, you can rebuild mozilla with the same command you used before to build firefox without xforms. switch to the root of your source directory and start the build with make -f client.mk build after the build finishes, you'll have a xforms.xpi in obj-*/dist/xpi-stage/xforms.xpi. congratulations, you've successfully built your first mozilla xforms extension! the built xpi file will only install on a nightly snapshot from the same day or your self-built firefox v...
XForms Input Element - Archive of obsolete content
of this attribute gives a hint to the xforms processor as to which type of widget(s) to use to represent this control accesskey - used to specify the keyboard shortcut for focusing this control single-node binding special inputmode - not supported for this control incremental - supported. the default value is 'false'. mozilla extensions labelposition - only for boolean types: show the label before or after the checkbox (see below) type restrictions the input element can be bound to a node containing simple content of any data type except xsd:base64binary, xsd:hexbinray or any data type derived from these. representations the xforms input element can be represented by the following widgets for the spcified data types (or types derived from these data types): text field - the default wid...
...ance node will be updated when the control loses the focus. checkbox most often used when the form author only needs a simple 'true', 'false', '1', or '0' response from the user (xhtml/xul). characteristics used when the instance node is of type xsd:boolean or a type derived from it analogous widgets are <xhtml:input type="checkbox"/> and <xul:checkbox/> the corresponding label can be displayed before or after the checkbox by using the labelposition attribute. specific handling of attributes incremental - if "true" or this attribute is omitted from this element, then the instance node will be updated when the user checks or un-checks the checkbox. if "false" then the instance node will be updated when the checkbox loses the focus. labelposition - a mozilla xforms extension in the namespace h...
...ntal - if "true" or this attribute is omitted from this element, then the instance node will be updated when the user checks or un-checks the checkbox. if "false" then the instance node will be updated when the checkbox loses the focus. labelposition - a mozilla xforms extension in the namespace http://www.mozilla.org/projects/xfor...009/extensions. this attribute is optional, possible values are before and after. the default value if omitted is after. it controls the display of the label relative to the checkbox. before shows the label first, then the checkbox, after shows the checkbox, than the label. labelposition was introduced with mozilla xforms 0.8.8. before that, the default behavior was to display the label first, then the checkbox. since the introduction of labelposition, the behavior ...
Index - Game development
collision detection in 3d environments. followup articles will cover implementations in specific 3d libraries. 14 bounding volume collision detection with three.js 3d, games, javascript, webgl, bounding boxes, collision detection, three.js this article shows how to implement collision detection between bounding boxes and spheres using the three.js library. it is assumed that before reading this you have read our 3d collision detection introductory article first, and have basic knowledge about three.js. 15 3d games on the web games, graphics, needscontent, needsexample, webgl, webvr, three.js for rich gaming experiences on the web, the weapon of choice is webgl, which is rendered on html <canvas>. webgl is basically an opengl es 2.0 for the web — it's ...
... 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. 49 game over 2d, beginner, canvas, games, javascript, phaser, tutorial, game over 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. 50 initialize the framework 2d, beginner, canvas, games, html, javascript, phaser, tutorial before we can start writing the game's functionality, we need to create a basic structure to render the game inside. this can be done using html — the phaser framework will generate the required <canvas> element. 5...
...canvas, games, javascript, tutorial, collision, detection we have the bricks appearing on the screen already, but the game still isn't that interesting as the ball goes through them. we need to think about adding collision detection so it can bounce off the bricks and break them. 63 create the canvas and draw on it 2d, beginner, canvas, games, html, javascript, tutorial before we can start writing 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. 64 finishing up beginner, canvas, games, javascript, tutorial, lives, requestanimationframe there's always room for improvements in any game we write. for example, we can offer more than one life to the player. the...
Bounding volume collision detection with THREE.js - Game development
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. ...
... 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.torusknotgeometry(0.5, 0.1), new meshnormalmaterial({})); knot.geometry.computeboundingbox(); var knotbbox = new box3( knot.geometry.boundingbox.min, knot.geometry.boundingbox.max); note: the boundingbox property takes the geometry itself as reference, and not the mesh. so any transformations such as scale, position, etc. applied to the mes...
...re have a containspoint method to do this test. var point = new three.vector3(2, 4, 7); knotbbox.containspoint(point); box3 vs. box3 the box3.intersectsbox method is available for performing this test. knotbbox.intersectsbox(otherbox); note: this is different from the box3.containsbox method, which checks whether the box3 fully wraps another one. sphere vs. sphere in a similar fashion as before, there is a sphere.intersectssphere method to perform this test. knotbsphere.intersectssphere(othersphere); sphere vs. box3 unfortunately this test is not implemented in three.js, but we can patch sphere to implement a sphere vs. aabb intersection algorithm. // expand three.js sphere to support collision tests vs box3 // we are creating a vector outside the method scope to // avoid spawning a...
Building up a basic demo with Babylon.js - Game development
ent <title>, and some css to set the width and height of the <canvas> element (which babylon.js will use to render the content on) to fill the entire available viewport space. the first <script> element includes the babylon.js library in the page; we will write our example code in the second one. there is one helper variable already included, which will store a reference to the <canvas> element. before reading on, copy this code to a new text file and save it in your working directory as index.html. initialising the babylon.js engine we have to create a babylon.js engine instance first (passing it the <canvas> element to render on) before we start developing our game. add the following code to the bottom of your second <script> element: var engine = new babylon.engine(canvas); the babylon ...
...reate a scene by adding the following lines just below our previous code: var scene = new babylon.scene(engine); scene.clearcolor = new babylon.color3(0.8, 0.8, 0.8); thus, the scene is created and the second line sets the background color to light gray. creating a rendering loop to make the scene actually visible we have to render it. add these lines at the end of the <script> element, just before the closing </script>. var renderloop = function () { scene.render(); }; engine.runrenderloop(renderloop); we're using the engine's runrenderloop() method to execute the renderloop() function repeatedly on every frame — the loop will continue to render indefinitely until told to stop. creating a camera now the setup code is in place we need to think about implementing the standard scen...
...o breathe a little life into those shapes by animating them. animation we already used position and rotation to adjust the position of the shapes; we could also scale them. to show actual animation, we need to make changes to these values inside the rendering loop at the end of our code, so they are updated on every frame. define a helper variable — t — that we will use for animations, just before the renderloop, and decrement it on every frame inside the loop, like this: var t = 0; var renderloop = function () { scene.render(); t -= 0.01; // animation code goes here }; engine.runrenderloop(renderloop); the t variable will be incremented on every rendered frame. rotation applying rotation is as easy as adding this line at the end of the renderloop function: box.rotation.y...
Bounce off the walls - Game development
all bouncing off the top edge, so now let's think about the bottom edge: if(y + dy > canvas.height) { dy = -dy; } if the ball's y position is greater than the height of the canvas (remember that we count the y values from the top left, so the top edge starts at 0 and the bottom edge is at 320 pixels, the canvas' height), then bounce it off the bottom edge by reversing the y axis movement as before. we could merge those two statements into one to save on code verbosity: if(y + dy > canvas.height || y + dy < 0) { dy = -dy; } if either of the two statements is true, reverse the movement of the ball. bouncing off the left and right we have the top and bottom edge covered, so let's think about the left and right ones. it is very similar actually, all you have to do is to repeat the sta...
...t and right we have the top and bottom edge covered, so let's think about the left and right ones. ...
...0) { dy = -dy; } at this point you should insert the above code block into the draw() function, just before the closing curly brace. the ball keeps disappearing into the wall! test your code at this point, and you will be impressed — now we have a ball that bounced off all four edges of the canvas! we have another problem however — when the ball hits each wall it sinks into it slightly before changing direction: this is because we're calculating the collision point of the wall and the center of the ball, while we should be doing it for its circumference. the ball should bounce right after if touches the wall, not when it's already halfway in the wall, so let's adjust our statements a bit to include that. update the last code you added to this: if(x + dx > canvas.width-ballradius |...
Hoisting - MDN Web Docs Glossary: Definitions of Web-related terms
f hoisting suggests that variable and function declarations are physically moved to the top of your code, but this is not in fact what happens. instead, the variable and function declarations are put into memory during the compile phase, but stay exactly where you typed them in your code. learn more technical example one of the advantages of javascript putting function declarations into memory before it executes any code segment is that it allows you to use a function before you declare it in your code. for example: function catname(name) { console.log("my cat's name is " + name); } catname("tiger"); /* the result of the code above is: "my cat's name is tiger" */ the above code snippet is how you would expect to write the code for it to work. now, let's see what happens when we call th...
...this is because of how context execution works in javascript. ...
...ve is: "my cat's name is tiger" */ the above code snippet is how you would expect to write the code for it to work. now, let's see what happens when we call the function before we write it: catname("chloe"); function catname(name) { console.log("my cat's name is " + name); } /* the result of the code above is: "my cat's name is chloe" */ even though we call the function in our code first, before the function is written, the code still works. this is because of how context execution works in javascript. hoisting works well with other data types and variables. the variables can be initialized and used before they are declared. only declarations are hoisted javascript only hoists declarations, not initializations. if a variable is declared and initialized after using it, the value will b...
XInclude - MDN Web Docs Glossary: Definitions of Web-related terms
i=0; i < xincludes.length; i++) { var xinclude = xincludes[i]; var href = xinclude.getattribute('href'); var parse = xinclude.getattribute('parse'); var xpointer = xinclude.getattribute('xpointer'); var encoding = xinclude.getattribute('encoding'); // e.g., utf-8 // "text/xml or application/xml or matches text/*+xml or application/*+xml" before encoding (then utf-8) var accept = xinclude.getattribute('accept'); // header "accept: "+x var acceptlanguage = xinclude.getattribute('accept-language'); // "accept-language: "+x var xifallback = xinclude.getelementsbytagnamens('http://www.w3.org/2001/xinclude', 'fallback')[0]; // only one such child is allowed if (href === '' || href === null) { //...
...ll-formed document response responsenodes = [response.documentelement]; // put in array so can be treated the same way as the above } // prepend any node(s) (as xml) then remove xinclude for (j=0; j < responsenodes.length ; j++) { xincludeparent.insertbefore(responsenodes[j], xinclude); } xincludeparent.removechild(xinclude); } else if (responsetype === 'responsetext') { if (encname) { var encodingtype = response.match(pattern); if (encodingtype) { ...
...h response now (as plain text or xml) } } } catch (e) { // use xi:fallback if xinclude retrieval above failed var xifallbackchildren = xifallback.childnodes; // prepend any node(s) then remove xinclude for (j=0; j < xifallbackchildren.length ; j++) { xincludeparent.insertbefore(xifallbackchildren[j], xinclude); } xincludeparent.removechild(xinclude); } } } return docu; } ...
WAI-ARIA basics - Learn web development
hance accessibility where required. what is wai-aria? let's start by looking at what wai-aria is, and what it can do for us. a whole new set of problems as web apps started to get more complex and dynamic, a new set of accessibility features and problems started to appear. for example, html5 introduced a number of semantic elements to define common page features (<nav>, <footer>, etc.) before these were available, developers would simply use <div>s with ids or classes, e.g. <div class="nav">, but these were problematic, as there was no easy way to easily find a specific page feature such as the main navigation programmatically. the initial solution was to add one or more hidden links at the top of the page to link to the navigation (or whatever else), for example: <a href="#hidden" ...
..., only use it when necessary! note: also, try to make sure you test your site with a variety of real users — non-disabled people, people using screenreaders, people using keyboard navigation, etc. they will have better insights than you about how well it works. practical wai-aria implementations in the next section we'll look at the four areas in more detail, along with practical examples. before you continue, you should get a screenreader testing setup put in place, so you can test some of the examples as you go through. see our section on testing screenreaders for more information. signposts/landmarks wai-aria adds the role attribute to browsers, which allows you to add extra semantic value to elements on your site wherever they are needed. the first major area in which this is usefu...
...can navigate down to, meaning the selected content is easier to find. note: if there is anything you explicitly don't want screen readers to read out, you can give them the aria-hidden="true" attribute. test your skills! you've reached the end of this article, but can you remember the most important information? you can find some further tests to verify that you've retained this information before you move on — see test your skills: wai-aria. summary this article has by no means covered all that's available in wai-aria, but it should have given you enough information to understand how to use it, and know some of the most common patterns you will encounter that require it. ...
Fundamental CSS comprehension - Learn web development
objective: to test comprehension of fundamental css theory, syntax and mechanics. ...
... objective: to test comprehension of fundamental css theory, syntax and mechanics. ...
...he image to the right so that it sticks to the right hand side of the main business card contents, and give it a max-height of 100% (a clever trick that ensures that it will grow/shrink to stay the same height as its parent container, regardless of what height it becomes.) beware! there are two errors in the provided rulesets. using any technique that you know, track these down and fix them before moving on. new rulesets you need to write: write a ruleset that targets both the card header, and card footer, giving them both a computed total height of 50px (including a content height of 30px and padding of 10px on all sides.) but express it in ems. the default margin applied to the <h2> and <p> elements by the browser will interfere with our design, so write a rule that targets all the...
Sizing items in CSS - Learn web development
in the future. 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 the different ways we can size things in css. the natural or intrinsic size of things html elements have a natural size, set before they are affected by any css. a straightforward example 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 i...
...t size you will need to load the example in a new browser window that you can resize (as the embedded <iframe> that contains the example shown above is its viewport). open the example, resize the browser window, and observe what happens to the size of the box and text. sizing things according to the viewport can be useful in your designs. ...
...section to show before the rest of your content, making that part of your page 100vh high will push the rest of the content below the viewport, meaning that it will only appear once the document is scrolled. test your skills! we have covered a lot in this article, but can you remember the most important information? you can find some further tests to verify that you've retained this information before you move on — see test your skills: sizing. summary this lesson has given you a rundown of some key issues that you might run into when sizing things on the web. when you move onto css layout, sizing will become very important in mastering the different layout methods, so it is worth understanding the concepts here before moving on. previous overview: building blocks next in this mo...
Flexbox - Learn web development
ction the flexbox children are laid out in) — by default this is set to row, which causes them to be laid out in a row in the direction your browser's default language works in (left to right, in the case of an english browser). try adding the following declaration to your <section> rule: flex-direction: column; you'll see that this puts the items back in a column layout, much like they were before we added any css. before you move on, delete this declaration from your example. note: you can also lay out flex items in a reverse direction using the row-reverse and column-reverse values. experiment with these values too! wrapping one issue that arises when you have a fixed amount of width or height in your layout is that eventually your flexbox children will overflow their container, bre...
...s sit in the center of the main axis. the value we've used above, space-around, is useful — it distributes all the items evenly along the main axis, with a bit of space left at either end. there is another value, space-between, which is very similar to space-around except that it doesn't leave any space at either end. we'd like to encourage you to play with these values to see how they work before you continue. ordering flex items flexbox also has a feature for changing the layout order of flex items, without affecting the source order. this is another thing that is impossible to do with traditional layout methods. the code for this is simple: try adding the following css to your button bar example code: button:first-child { order: 1; } refresh, and you'll now see that the "smile" b...
...e. not supporting flexbox features however will probably break a layout completely, making it unusable. we discuss strategies for overcoming cross browser support issues in our cross browser testing module. test your skills! we have covered a lot in this article, but can you remember the most important information? you can find some further tests to verify that you've retained this information before you move on — see test your skills: flexbox. summary that concludes our tour of the basics of flexbox. we hope you had fun, and will have a good play around with it as you travel forward with your learning. next we'll have a look at another important aspect of css layouts — css grids. previous overview: css layout next in this module introduction to css layout normal flow fl...
Introduction to CSS layout - Learn web development
tely remove an element from normal flow, and place it using offsets from the edges of a containing block. going back to our original non-positioned example, we could add the following css rule to implement absolute positioning: .positioned { position: absolute; top: 30px; left: 30px; } here we give our middle paragraph a position value of absolute, and the same top and left properties as before. adding this code, however, will give the following result: absolute positioning example <h1>absolute positioning</h1> <p>i am a basic block level element.</p> <p class="positioned">this is my absolutely positioned element.</p> <p>i am a basic block level element.</p> body { width: 500px; margin: 0 auto; } p { background-color: rgb(207,232,220); border: 2px solid rgb(79,185,227...
...00px; margin: 0 auto; } .positioned { background: rgba(255,84,104,.3); border: 2px solid rgb(255,84,104); padding: 10px; margin: 10px; border-radius: 5px; } .positioned { position: sticky; top: 30px; left: 30px; } note: to find more out about positioning, see our positioning article. table layout html tables are fine for displaying tabular data, but many years ago — before even basic css was supported reliably across browsers — web developers used to also use tables for entire web page layouts — putting their headers, footers, different columns, etc. in various table rows and columns. this worked at the time, but it has many problems — table layouts are inflexible, very heavy on markup, difficult to debug, and semantically wrong (e.g., screen reader users hav...
...o line up nicely by default. all we then have to do is add a bit of sizing, margin, etc. to make everything look a bit nicer and we're done. you'll notice that the caption paragraph has been given display: table-caption; — which makes it act like a table <caption> — and caption-side: bottom; to tell the caption to sit on the bottom of the table for styling purposes, even though the markup is before the <input> elements in the source. this allows for a nice bit of flexibility. html { font-family: sans-serif; } form { display: table; margin: 0 auto; } form div { display: table-row; } form label, form input { display: table-cell; margin-bottom: 10px; } form label { width: 200px; padding-right: 5%; text-align: right; } form input { width: 300px; } form p { display: ...
Legacy layout methods - Learn web development
you imagine your layout as a set number of columns (e.g. 4, 6, or 12), and then fit your content columns inside these imaginary columns. in this article we'll explore how these older methods work, in order that you understand how they were used if you work on an older project. ...
...hat you understand how they were used if you work on an older project. prerequisites: html basics (study introduction to html), and an idea of how css works (study introduction to css and styling boxes.) objective: to understand the fundamental concepts behind the grid layout systems used prior to css grid layout being available in browsers. layout and grid systems before css grid layout it may seem surprising to anyone coming from a design background that css didn’t have an inbuilt grid system until very recently, and instead we seemed to be using a variety of sub-optimal methods to create grid-like designs. we now refer to these as "legacy" methods. for new projects, in most cases css grid layout will be used in combination with one or more other modern layo...
...ike so: .content { width: calc((6.25%*8) + (2.08333333%*7)); } note: if you were to use a preprocessor such as sass, you could create a simple mixin to insert that value for you. enabling offset containers in our grid the grid we have created works well as long as we want to start all of the containers flush with the left hand side of the grid. if we wanted to leave an empty column space before the first container — or between containers — we would need to create an offset class to add a left margin to our site to push it across the grid visually. more math! let's try this out. start with your previous code, or use our fluid-grid.html file as a starting point. let's create a class in our css that will offset a container element by one column width. add the following to the bottom...
Normal Flow - Learn web development
previous overview: css layout next this article explains normal flow, or the way that webpage elements lay themselves out if you have not changed their layout. prerequisites: the basics of html (study introduction to html), and an idea of how css works (study introduction to css.) objective: to explain how browsers layout web pages by default, before we begin to make changes. as detailed in the last lesson introducing layout, elements on a webpage lay out in the normal flow, if you have not applied any css to change the way they behave. and, as we began to discover, you can change how elements behave either by adjusting their position in that normal flow, or removing them from it altogether. starting with a solid, well-structured document that is readabl...
...is the best way to begin any webpage. it ensures that your content is readable, even if the user is using a very limited browser or a device such as a screen reader that reads out the content of the page. in addition, as normal flow is designed to make a readable document, by starting in this way you are working with the document rather than fighting against it as you make changes to the layout. before digging deeper into different layout methods, it is worth revisiting some of the things you will have studied in previous modules with regard to normal document flow. 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 loo...
...ntent, as long as there is space for them to do so inside the width of the parent block level element. if there isn't space, then the overflowing text or elements will move down to a new line. if two adjacent elements both have the margin set on them and the two margins touch, the larger of the two remains, and the smaller one disappears — this is called margin collapsing, and we have met this before too. let's look at a simple example that explains all of this: <h1>basic document flow</h1> <p>i am a basic block level element. my adjacent block level elements sit on new lines below me.</p> <p>by default we span 100% of the width of our parent element, and we are as tall as our child content. our total width and height is our content + padding + border width/height.</p> <p>we are separat...
CSS layout - Learn web development
so we can now dive deep into css layout, looking at different display settings, modern layout tools like flexbox, css grid, and positioning, and some of the legacy techniques you might still want to know about. looking to become a front-end web developer? we have put together a course that includes all the essential information you need to work towards your goal. get started prerequisites before starting this module, you should already: have basic familiarity with html, as discussed in the introduction to html module. be comfortable with css fundamentals, as discussed in introduction to css. understand how to style boxes. 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 examp...
...that. this article explains the basics of normal flow as a grounding for learning how to change it. flexbox flexbox is a one-dimensional layout method for laying out items in rows or columns. items flex to fill additional space and shrink to fit into smaller spaces. this article explains all the fundamentals. after studying this guide you can test your flexbox skills to check your understanding before moving on. grids css grid layout is a two-dimensional layout system for the web. it lets you lay content out in rows and columns, and has many features that make building complex layouts straightforward. this article will give you all you need 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 ...
...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. legacy layout methods grid systems are a very common feature used in css layouts, and before css grid layout they tended to be implemented using floats or other layout features. you imagine your layout as a set number of columns (e.g. 4, 6, or 12), and then fit your content columns inside these imaginary columns. in this article we'll explore how these older methods work, in order that you understand how they were used if you work on an older project. supporting older browsers in thi...
Styling links - Learn web development
s: 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 think carefully before turning it off; you should at least double up the styles given to the link hover state on the focus state too. note: you are not just limited to the above properties to style your links — you are free to use any properties you like. just try not to go too crazy! styling some links now we've looked at the default states in some detail, let's look at a typical set of link styles. to start ...
... } a:visited { color: purple; } a:focus, a:hover { border-bottom: 1px solid; } a:active { color: red; } a[href*="http"] { background: url('https://mdn.mozillademos.org/files/12982/external-link-52.png') no-repeat 100% 0; background-size: 16px 16px; padding-right: 19px; } so what's going on here? we'll skip over most of the css, as it's just the same information you've looked at before. the last rule however is interesting — here we are inserting a custom background image on external links in a similar manner to how we handled custom bullets on list items in the last article — this time however we are using background shorthand instead of the individual properties. we set the path to the image we want to insert, specify no-repeat so we only get one copy inserted, and then s...
...icle, and already did some skill testing in our active learning sections, but can you remember the most important information going forward? you can find an assessment to verify that you've retained this information at the end of the module — see typesetting a community school homepage. this assessment tests all the knowledge discussed in this module, so you might want to read the next article before moving on to it. summary we hope this article has provided you with all you'll need to know about links — for now! the final article in our styling text module details how to use custom fonts on your websites, or web fonts as they are better known. previous overview: styling text next in this module fundamental text and font styling styling lists styling links web fonts types...
Basic native form controls - Learn web development
olor pickers). note: you can find examples of all the single line text field types on github at single-line-text-fields.html (see it live also). here is a basic single line text field example: <input type="text" id="comment" name="comment" value="i'm a text field"> single line text fields have only one true constraint: if you type text with line breaks, the browser removes those line breaks before sending the data to the server. the following screenshot shows default, focused and disabled text input types in firefox 71 and safari on macos and in chrome 79 and edge 18 on windows 10. note: html5 enhanced the basic original single line text field by adding special values for the type attribute that enforce specific validation constraints and other features, for example specific to enteri...
...terface feature; unless you submit your form securely, it will get sent in plain text, which is bad for security — a malicious party could intercept your data and steal passwords, credit card details, or whatever else you've submitted. the best way to protect users from this is to host any pages involving forms over a secure connection (i.e. at an https:// ... address), so the data is encrypted before it is sent. browsers recognize the security implications of sending form data over an insecure connection, and have warnings to deter users from using insecure forms. for more information on what firefox implements, see insecure passwords. hidden content another original text control is the hidden input type. this is used to create a form control that is invisible to the user, but is still sen...
... it is outside of, even if it is inside a different form element. name the name of the element; this is submitted with the form data. value the element's initial value. test your skills! you've reached the end of this article, but can you remember the most important information? you can find some further tests to verify that you've retained this information before you move on — see test your skills: basic controls. summary this article has covered the older input types — the original set introduced in the early days of html that is well supported in all browsers. in the next section, we'll take a look at the newer values of the type attribute that were added in html5. previous overview: forms next in this module your first form how to s...
HTML forms in legacy browsers - Learn web development
de to ensure consistency among all your form controls so user experience is not destroyed. you can also investigate some hard techniques such as rebuilding widgets with javascript. but in that case, do not hesitate to charge your client for such foolishness. feature detection and polyfills css and javascript are awesome technologies, but it's important to ensure you don't break legacy browsers. ...
...ues such as rebuilding widgets with javascript. but in that case, do not hesitate to charge your client for such foolishness. feature detection and polyfills css and javascript are awesome technologies, but it's important to ensure you don't break legacy browsers. ...
... all browsers. as a last reminder, just always think about the end users. conclusion as you can see, considering browser and operating system default form control appearance is important. there are many techniques to handle these issue; however mastering all of them is beyond the scope of this article. the basic premise is to consider whether altering the default implemenation is worth the work before embarking on the challenge. if you read all the articles of this html forms guide, you should now be at ease with using forms. ...
How to structure a web form - Learn web development
<legend> element just below the opening <fieldset> tag. the text content of the <legend> formally describes the purpose of the <fieldset> it is included inside. many assistive technologies will use the <legend> element as if it is a part of the label of each control inside the corresponding <fieldset> element. for example, some screen readers such as jaws and nvda will speak the legend's content before speaking the label of each control. here is a little example: <form> <fieldset> <legend>fruit juice size</legend> <p> <input type="radio" name="size" id="size_1" value="small"> <label for="size_1">small</label> </p> <p> <input type="radio" name="size" id="size_2" value="medium"> <label for="size_2">medium</label> </p> <p> <input type="radi...
...username" type="text" name="username"> <abbr title="required" aria-label="required">*</abbr> </label> </div> <!-- but this is probably best: --> <div> <label for="username">name: <abbr title="required" aria-label="required">*</abbr></label> <input id="username" type="text" name="username"> </div> the paragraph at the top states a rule for required elements. the rule must be included before it is used so that sighted users and users of assistive technologies such as screen readers can learn what it means before they encounter a required element. while this helps inform users what an asterisk means, it can not be relied upon. a screen reader will speak an asterisk as "star" when encountered. when hovered by a sighted mouse user, "required" should appear, which is achieved by use of...
... summary you now have all the knowledge you'll need to properly structure your web forms. we will cover many of the features introduced here in the next few articles, with the next article looking in more detail at using all the different types of form widgets you'll want to use to collect information from your users. see also a list apar...
Creating hyperlinks - Learn web development
all users, for example by putting it in the regular text. active learning: creating your own example link create an html document using your local code editor and our getting started template. inside the html body, add one or more paragraphs or other types of content you already know about. change some of the content into links. include title attributes. block level links as mentioned before, almost any content can be made into a link, even block-level elements. if you have an image you want to make into a link, use the <a> element and reference the image file with the <img> element. <a href="https://www.mozilla.org/"> <img src="mozilla-image.png" alt="mozilla logo that links to the mozilla homepage"> </a> note: you'll find out more about using images on the web in a future arti...
...e same directory as the current file. the url you would use is contacts.html: <p>want to contact a specific staff member? find details on our <a href="contacts.html">contacts page</a>.</p> moving down into subdirectories: if you wanted to include a hyperlink inside index.html (the top level index.html) pointing to projects/index.html, you would need to go down into the projects directory before indicating the file you want to link to. this is done by specifying the directory's name, then a forward slash, then the name of the file. the url you would use is projects/index.html: <p>visit my <a href="projects/index.html">project homepage</a>.</p> moving back up into parent directories: if you wanted to include a hyperlink inside projects/index.html pointing to pdfs/project-brief.pd...
... summary that's it for links, for now anyway! you'll return to links later on in the course when you start to look at styling them. next up for html, we'll return to text semantics and look at some more advanced/unusual features that you'll find useful — advanced text formatting is your next stop. previous overview: introduction to html next ...
HTML text fundamentals - Learn web development
this would look like so: <ol> <li>remove the skin from the garlic, and chop coarsely.</li> <li>remove all the seeds and stalk from the pepper, and chop coarsely.</li> <li>add all the ingredients i...
... far have clearcut associated semantics. the situation with <b>, <i>, and <u> is somewhat more complicated. they came about so people could write bold, italics, or underlined text in an era when css was still supported poorly or not at all. elements like this, which only affect presentation and not semantics, are known as presentational elements and should no longer be used, because as we've seen before, semantics is so important to accessibility, seo, etc. html5 redefined <b>, <i>, and <u> with new, somewhat confusing, semantic roles. here's the best rule of thumb: it's likely appropriate to use <b>, <i>, or <u> to convey a meaning traditionally conveyed with bold, italics, or underline, provided there is no more suitable element. however, it always remains critical to keep an accessibility m...
... a set of instructions --> <ol> <li> <b>slice</b> two pieces of bread off the loaf. </li> <li> <b>insert</b> a tomato slice and a leaf of lettuce between the slices of bread. </li> </ol> test your skills! you've reached the end of this article, but can you remember the most important information? you can find some further tests to verify that you've retained this information before you move on—see test your skills: html text basics. summary that's it for now! this article should have given you a good idea of how to start marking up text in html, and introduced you to some of the most important elements in this area. there are a lot more semantic elements to cover in this area, and we'll look at a lot more in our advanced text formatting article, later on in the course. ...
Making asynchronous programming easier with async and await - Learn web development
et objecturl = url.createobjecturl(blob); let image = document.createelement('img'); image.src = objecturl; document.body.appendchild(image); }).catch(e => console.log(e)); you can try typing in the example yourself, or running our live example (see also the source code). but how does it work? you'll note that we've wrapped the code inside a function, and we've included the async keyword before the function keyword. this is necessary — you have to create an async function to define a block of code in which you'll run your async code; as we said earlier, await only works inside of async functions. inside the myfetch() function 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...
...o define a block of code in which you'll run your async code; as we said earlier, await only works inside of async functions. inside the myfetch() function definition you can see that the code closely resembles the previous promise version, but there are some differences. instead of needing to chain a .then() block on to the end of each promise-based method, you just need to add an await keyword before the method call, and then assign the result to a variable. the await keyword causes the javascript runtime to pause your code on this line, allowing other code to execute in the meantime, until the async function call has returned its result. once that's complete, your code continues to execute starting on the next line. for example: let response = await fetch('coffee.jpg'); the response return...
...the promises will all fulfill at the same time; when you run the second example, you'll see the alert box reporting a total run time of just over 3 seconds! you'll have to test your code carefully, and bear this in mind if performance starts to suffer. another minor inconvenience is that you have to wrap your awaited promises inside an async function. async/await class methods as a final note before we move on, you can even add async in front of class/object methods to make them return promises, and await promises inside them. take a look at the es class code we saw in our object-oriented javascript article, and then look at our modified version with an async method: class person { constructor(first, last, age, gender, interests) { this.name = { first, last }; this...
Asynchronous JavaScript - Learn web development
blocking operations such as fetching resources from a 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 asynchronous javascript is a fairly advanced topic, and you are advised to work through javascript first steps and javascript building blocks modules before attempting this. if you are not familiar with the concept of asynchronous programming, you should definitely start with the general asynchronous programming concepts article in this module. if you are, then you can probably skip to the introducing asynchronous javascript module. note: if you are working on a computer/tablet/other device where you don't have the ability to create your own files...
...e you don't have the ability to create your own files, you can try out (most of) the code examples in an online coding program such as jsbin or glitch. guides general asynchronous programming concepts in this article we'll run through a number of important concepts relating to asynchronous programming, and how this looks in web browsers and javascript. you should understand these concepts before working through the other articles in the module. introducing asynchronous javascript in this article we briefly recap the problems associated with sychronous javascript, and take a first look at some of the different asynchronous javascript techniques you'll encounter, showing how they can help us solve such problems. cooperative asynchronous javascript: timeouts and intervals here we look...
...webapis, and how to write your own. making asynchronous programming easier with async and await promises can be somewhat complex to set up and understand, and so modern browsers have implemented async functions and the await operator. the former allows standard functions to implicitly behave asynchronously with promises, whereas the latter can be used inside async functions to wait for promises before the function continues. this makes chaining promises simpler and easier to read. choosing the right approach to finish this module off, we'll consider the different coding techniques and features we've discussed throughout, looking at which ones you should use when, with recommendations and reminders of common pitfalls where appropriate. ...
Build your own function - Learn web development
objective: to provide some practice in building a custom function, and explain a few more useful associated details. active learning: let's build a function the custom function we are going to build will be called displaymessage(). it will display a custom message box on a web page and will act as a customized replacement for a browser's built-in alert() function. we've seen this before, but let's just refresh our memories. type the following in your browser's javascript console, on any page you like: alert('this is a message'); the alert function takes a single argument — the string that is displayed in the alert box. try varying the string to change the message. the alert function is limited: you can alter the message, but you can't easily vary anything else, such as the ...
...s without the button being clicked! the parentheses in this context are sometimes called the "function invocation operator". you only use them when you want to run the function immediately in the current scope. in the same respect, the code inside the anonymous function is not run immediately, as it is inside the function scope. if you tried the last experiment, make sure to undo the last change before carrying on. improving the function with parameters as it stands, the function is still not very useful — we don't want to just show the same default message every time. let's improve our function by adding some parameters, allowing us to call it with some different options. first of all, update the first line of the function: function displaymessage() { to this: function displayme...
...o) little function is becoming. note: if you have trouble getting the example to work, feel free to check your code against the finished version on github (see it running live also), or ask us for help. test your skills! you've reached the end of this article, but can you remember the most important information? you can find some further tests to verify that you've retained this information before you move on — see test your skills: functions. these tests require skills that are covered in the next article, so you might want to read those first before trying it. conclusion congratulations on reaching the end! this article took you through the entire process of building up a practical custom function, which with a bit more work could be transplanted into a real project. in the next arti...
Introduction to web APIs - Learn web development
they work. they are based on objects your code interacts with apis using one or more javascript objects, which serve as containers for the data the api uses (contained in object properties), and the functionality the api makes available (contained in object methods). note: if you are not already familiar with how objects work, you should go back and work through our javascript objects module before continuing. let's return to the example of the web audio api — this is a fairly complex api, which consists of a number of objects. the most obvious ones are: audiocontext, which represents an audio graph that can be used to manipulate audio playing inside the browser, and has a number of methods and properties available to manipulate that audio. mediaelementaudiosourcenode, which represe...
... our bouncing balls demo (see it running live also). they use events to handle changes in state we already discussed events earlier on in the course in our introduction to events article, which looks in detail at what client-side web events are and how they are used in your code. if you are not already familiar with how client-side web api events work, you should go and read this article first before continuing. some web apis contain no events, but most contain at least a few. the handler properties that allow us to run functions when events fire are generally listed in our reference material in separate "event handlers" sections. we already saw a number of event handlers in use in our web audio api example above. to provide another example, instances of the xmlhttprequest object (each one...
...g and we really shouldn't be subjecting our users to it. note: depending on how strict the browser is, such security mechanisms might even stop the example from working locally, i.e. if you load the local example file in your browser instead of running it from a web server. at the time of writing, our web audio api example wouldn't work locally on google chrome — we had to upload it to github before it would work. summary at this point, you should have a good idea of what apis are, how they work, and what you can do with them in your javascript code. you are probably excited to start actually doing some fun things with specific apis, so let's go! next up, we'll look at manipulating documents with the document object model (dom). overview: client-side web apis next in this module ...
Video and Audio APIs - Learn web development
this is an icon font — all the characters of the alphabet equate to common icons you might want to use in an application. next we use generate...
... position: relative; content: attr(data-icon); color: #aaa; text-shadow: 1px 1px 0px black; } first of all, at the top of the css we use a @font-face block to import a custom web font. this is an icon font — all the characters of the alphabet equate to common icons you might want to use in an application. next we use generated content to display an icon on each button: we use the ::before selector to display the content before each <button> element. we use the content property to set the content to be displayed in each case to be equal to the contents of the data-icon attribute. in the case of our play button, data-icon contains a capital "p". we apply the custom web font to our buttons using font-family. in this font, "p" is actually a "play" icon, so therefore the play button ...
...wd/fwd button functionality and play/stop the video as you'd expect? this is fairly easy to fix. first of all, add the following lines inside the stopmedia() function — anywhere will do: rwd.classlist.remove('active'); fwd.classlist.remove('active'); clearinterval(intervalrwd); clearinterval(intervalfwd); now add the same lines again, at the very start of the playpausemedia() function (just before the start of the if statement). at this point, you could delete the equivalent lines from the windbackward() and windforward() functions, as that functionality has been implemented in the stopmedia() function instead. note: you could also further improve the efficiency of the code by creating a separate function that runs these lines, then calling that anywhere it is needed, rather than repeati...
Silly story generator - Learn web development
objective: to test comprehension of javascript fundamentals, such as variables, numbers, operators, strings, and arrays. ...
...ded with some raw html/css and a few text strings and javascript functions; you need to write the necessary javascript to turn this into a working program, which does the following: generates a silly story when the "generate random story" button is pressed. replaces the default name "bob" in the story with a custom name, only if a custom name is entered into the "enter custom name" text field before the generate button is pressed. converts the default us weight and temperature quantities and units in the story into uk equivalents if the uk radio button is checked before the generate button is pressed. will generate another random silly story if you press the button again (and again...) the following screenshot shows an example of what the finished program should output: to give you mo...
... to give you more of an idea, have a look at the finished example (no peeking at the source code!) steps to complete the following sections describe what you need to do. basic setup: create a new file called main.js, in the same directory as your index.html file. apply the external javascript file to your html by inserting a <script> element into your html referencing main.js. put it just before the closing </body> tag. initial variables and functions: in the raw text file, copy all of the code underneath the heading "1. complete variable and function definitions" and paste it into the top of the main.js file. this gives you three variables that store references to the "enter custom name" text field (customname), the "generate random story" button (randomize), and the <p> element at...
Handling text — strings in JavaScript - Learn web development
s, or miss one of the quotes, you'll get an error. try entering the following lines: let badstring = this is a test; let badstring = 'this is a test; let badstring = this is a test'; these lines don't work because any text without quotes around it is assumed to be a variable name, property name, a reserved word, or similar. if the browser can't find it, then an error is raised (e.g. "missing; before statement"). if the browser can see where a string starts, but can't find the end of the string, as indicated by the 2nd quote, it complains with an error (with "unterminated string literal"). if your program is raising such errors, then go back and check all your strings to make sure you have no missing quote marks. the following will work if you previously defined the variable string — try i...
...: let bigmouth = 'i've got no right to take my place...'; this leads us very nicely into our next subject. escaping characters in a string to fix our previous problem code line, we need to escape the problem quote mark. escaping characters means that we do something to them to make sure they are recognized as text, not part of the code. in javascript, we do this by putting a backslash just before the character. try this: let bigmouth = 'i\'ve got no right to take my place...'; bigmouth; this works fine. you can escape other characters in the same way, e.g. \", and there are some special codes besides. see escape notation for more details. concatenating strings concatenate is a fancy programming word that means "join together". joining together strings in javascript uses the plus (+...
...ny of our examples still use standard string literals, but we will include more template literals going forward. see our template literals reference page for more examples and details of advanced features. test your skills! you've reached the end of this article, but can you remember the most important information? you can find some further tests to verify that you've retained this information before you move on — see test your skills: strings. note that this also requires knowledge from the next article, so you might want to read that first. conclusion so that's the very basics of strings covered in javascript. in the next article, we'll build on this, looking at some of the built-in methods available to strings in javascript and how we can use them to manipulate our strings into just th...
Useful string methods - Learn web development
nipulate strings. strings as objects most things are objects in javascript. when you create a string, for example by using let string = 'this is my string'; your variable becomes a string object instance, and as a result has a large number of properties and methods available to it. you can see this if you go to the string object page and look down the list on the side of the page! now, before your brain starts melting, don't worry! you really don't need to know about most of these early on in your learning journey. but there are a few that you'll potentially use quite often that we'll look at here. let's enter some examples into the browser developer console. finding the length of a string this is easy — you simply use the length property. try entering the following lines: let ...
...ptional: if you don't include it, the slice ends at the end of the original string. there are other options too; study the slice() page to see what else you can find out. changing case the string methods tolowercase() and touppercase() take a string and convert all the characters to lower- or uppercase, respectively. this can be useful for example if you want to normalize all user-entered data before storing it in a database. let's try entering the following lines to see what happens: let raddata = 'my name is mud'; raddata.tolowercase(); raddata.touppercase(); updating parts of a string you can replace one substring inside a string with another substring using the replace() method. this works very simply at a basic level, although there are some advanced things you can do with it that we...
... conclusion you can't escape the fact that being able to handle words and sentences in programming is very important — particularly in javascript, as websites are all about communicating with people. this article has given you the basics that you need to know about manipulating strings for now. this should serve you well as you go into more comple...
JavaScript First Steps - Learn web development
we have put together a course that includes all the essential information you need to work towards your goal. ...
... introduction to html. introduction to css. ...
... introduction to html. introduction to css. ...
Adding features to our bouncing balls demo - Learn web development
previous overview: objects in this assessment, you are expected to use the bouncing balls demo from the previous article as a starting point, and add some new and interesting features to it. prerequisites: before attempting this assessment you should have already worked through all the articles in this module. objective: to test comprehension of javascript objects and object-oriented constructs starting point to get this assessment started, make a local copy of index-finished.html, style.css, and main-finished.js from our last article in a new directory in your local computer. alternatively, you could use a site like jsbin or glitch to do your assessment. you could paste the html, css and javascript into one of these online editors. if the online editor ...
...t. 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. note: if you get stuck, then ask us for help — see the assessment or further help section at the bottom of this page. hints and tips a couple of pointers before you get started. this assessment is quite challenging. read the whole assessment before you start coding, and take each step slowly and carefully. it might be a good idea to save a separate copy of the demo after you get each stage working, so you can refer back to it if you find yourself in trouble later on. project brief our bouncy ball demo is fun, but now we want to make it a little bi...
...onstructor should inherit the x, y, velx, vely, and exists properties from the shape() constructor. it should also define a color and a size property, like the original ball() constructor did. remember to set the ball() constructor's prototype and constructor appropriately. the ball draw(), update(), and collisiondetect() method definitions should be able to stay exactly the same as they were before. you also need to add a new parameter to the new ball() ( ... ) constructor call — the exists parameter should be the 5th parameter, and should be given a value of true. at this point, try reloading the code — it should work just the same as it did before, with our redesigned objects. defining evilcircle() now it's time to meet the bad guy — the evilcircle()! our game is only going to i...
JavaScript — Dynamic client-side scripting - Learn web development
aps, 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. before attempting to learn javascript, you are strongly advised to get familiar with at least these two technologies first, and perhaps others as well. start by working through the following modules: getting started with the web introduction to html introduction to css having previous experience with other programming languages might also help. after getting familiar with the basics of javascrip...
... learn about more advanced topics, for example: javascript in depth, as taught in our javascript guide web apis modules this topic contains the following modules, in a suggested order for working through them. javascript first steps in our first javascript module, we first answer some fundamental questions such as "what is javascript?", "what does it look like?", and "what can it do?", before moving on to taking you through your first practical experience of writing javascript. after that, we discuss some key javascript features in detail, such as variables, strings, numbers and arrays. javascript building blocks in this module, we continue our coverage of all javascript's key fundamental features, turning our attention to commonly-encountered types of code block such as conditional...
...jects, and explain what json data is and how to work with it. asynchronous javascript in this module we take a look at asynchronous javascript, why it is important, and how it can be used to effectively handle potential blocking operations such as fetching resources from a server. client-side web apis when writing client-side javascript for web sites or applications, you won't go very far before you start to use apis — interfaces for manipulating different aspects of the browser and operating system the site is running on, or even data from other web sites or services. in this module we will explore what apis are, and how to use some of the most common apis you'll come across often in your development work. solving common javascript problems use javascript to solve common problems ...
Getting started with React - Learn web development
g variables). variables in jsx back in app.js, let’s focus on line 9: <img src={logo} classname="app-logo" alt="logo" /> here, the <img /> tag's src attribute value is in curly braces. this is how jsx recognizes variables. react will see {logo}, know you are referring to the logo import on line 2 of our app, then retrieve the logo file and render it. let's try making a variable of our own. before the return statement of app, add const subject = 'react';. your app component should now look like this: function app() { const subject = "react"; return ( <div classname="app"> <header classname="app-header"> <img src={logo} classname="app-logo" alt="logo" /> <p> hello, world! </p> </header> </div> ); } change line 8 to use our subjec...
...s like this (with the return statement shortened for brevity): function app() { const subject = "react"; return ( // return statement ); } change the signature of the app function so that it accepts props as a parameter, and delete the subject const. just like any other function parameter, you can put props in a console.log() to print it to your browser's console. go ahead and do that before the return statement, like so: function app(props) { console.log(props); return ( // return statement ); } save your file and check your browser's javascript console. you should see something like this logged: object { subject: "clarice" } the object property subject corresponds to the subject prop we added to our <app /> component call, and the string clarice corresponds to its val...
...; } when you save, the app should now greet you with "hello, clarice!". if you return to index.js, edit the value of subject, and save, your text will change. summary this brings us to the end of our initial look at react, including how to install it locally, creating a starter app, and how the basics work. in the next article, we'll start building our first proper application — a todo list. before we do that, however, let's recap some of the things we’ve learned. in react: components can import modules they need and must export themselves at the bottom of their files. component functions are named with pascalcase. you can read jsx variables by putting them between curly braces, like {so}. some jsx attributes are different than html attributes so that they don't conflict with javas...
Dynamic behavior in Svelte: working with variables and props - Learn web development
now let's do something with that information. let's start by showing a status message. find the <h2> heading with an id of list-heading and replace the hardcoded number of active and completed tasks with dynamic expressions: <h2 id="list-heading">{completedtodos} out of {totaltodos} items completed</h2> go to the app, and you should see the "2 out of 3 items completed" message as before, but this time the information is coming from the todos array. to prove it, go to that array, and try changing some of the todo object's completed property values, and even add a new todo object. observe how the numbers in the message are updated appropriately. dynamically generating the todos from the data at the moment, our displayed todo items are all static. we want to iterate over...
...eted: true }, { id: 3, name: 'complete the rest of the tutorial', completed: false } ] </script> <todos todos={todos} /> when the attribute and the variable have the same name, svelte allows you to just specify the variable as a handy shortcut, so we can rewrite our last line like this. try this now. <todos {todos} /> at this point your todos should render just like they did before, except that now we're passing them in from the app.svelte component. toggling and removing todos let's add some functionality to toggle the task status. svelte has the on:eventname directive for listening to dom events. let's add a handler to the on:click event of the checkbox input to toggle the completed value. update the <input type="checkbox"> element inside src/components/todos.svel...
...t soon. now we want to update our html so that we call addtodo() whenever the form is submitted. update the newtodo form's opening tag like so: <form on:submit|preventdefault={addtodo}> the on:eventname directive supports adding modifiers to the dom event with the | character. in this case, the preventdefault modifier tells svelte to generate the code to call event.preventdefault() before running the handler. explore the previous link to see what other modifiers are available. if you try adding new todos at this point, the new todos are added to the todos array but our ui is not updated. remember that in svelte reactivity is triggered with assignments. that means that the addtodo() function is executed, the element is added to the todos array, but svelte won't detect that th...
Adding a new todo form: Vue events, methods, and models - Learn web development
ls, and methods. creating a new to-do form we now have an app that displays a list of to-do items. however, we can't update our list of items without manually changing our code! let's fix that. let's create a new component that will allow us to add a new to-do item. in your components folder, create a new file called todoform.vue. add a blank <template> and a <script> tag like before: <template></template> <script> export default {}; </script> let's add in an html form that lets you enter a new todo item and submit it into the app. we need a <form> with a <label>, an <input>, and a <button>. update your template as follows: <template> <form> <label for="new-todo-input"> what needs to be done? </label> <input type="text" id="new-t...
... some text to the <input> field, and click the "add" button. you should see the value you entered logged to your console, for example: label value: my value changing v-model behavior with modifiers in a similar fashion to event modifiers, we can also add modifiers to change the behavior of v-model. in our case, there are two worth considering. the first, .trim, will remove whitespace from before or after the input. we can add the modifier to our v-model statement like so: v-model.trim="label". the second modifier we should consider is called .lazy. this modifier changes when v-model syncs the value for text inputs. as mentioned earlier, v-model syncing works by updating the variable using events. for text inputs, this sync happens using the input event. often, this means that vue is syn...
...odoitems array. this can be done by pushing a new to-do item object to the array containing our new data. update your addtodo() method like so: addtodo(todolabel) { this.todoitems.push({id:uniqueid('todo-'), label: todolabel, done: false}); } try testing your form again, and you should see new to-do items get appended to the end of the list. let's make a further improvement before we move on. if you submit the form while the input is empy, todo items with no text still get added to the list. to fix that, we can prevent the todo-added event from firing when name is empty. since name is already being trimmed by the .trim directive, we only need to test for the empty string. go back to your todoform component, and update the onsubmit() method like so. if the label value is...
Handling common HTML and CSS problems - Learn web development
mall to read, or perhaps the site is slow because of expensive animations. let's go forth and look at how we can reduce cross browser errors that result from html/css. first things first: fixing general problems we said in the first article of this series that a good strategy to begin with is to test in a couple of modern browsers on desktop/mobile, to make sure your code is working generally, before going on to concentrate on the cross browser issues. in our debugging html and debugging css articles, we provided some really basic guidance on debugging html/css — if you are not familiar with the basics, you should definitely study these articles before carrying on. basically, it is a matter of checking whether your html and css code is well formed and doesn't contain any syntax errors. ...
...local copy of selectivizr-example-start.html. if you look at this running live, you'll see that it contains two paragraphs, one of which is styled. we've selected the paragraph with p:first-child, which won't work in old versions of ie. now download mootools and selectivizr, and save them in the same directory as your sample html. put the following code into the head of your html document, just before the opening <style> tag: <script type="text/javascript" src="mootools-core-1.6.0.js"></script> <!--[if (gte ie 6)&(lte ie 8)]> <script type="text/javascript" src="selectivizr-min.js"></script> <![endif]--> if you try running this in an old version of ie, it should work fine. handling css prefixes another set of problems comes with css prefixes — these are a mechanism ori...
...ternal resource links. for example, see http://caniuse.com/#search=video (you just have to enter the feature you are searching for into the text box). stackoverflow.com (so) is a forum site where you can ask questions and have fellow developers share their solutions, look up previous posts, and help other developers. you are advised to look and see if there is an answer to your question already, before posting a new question. for example, we searched for "cross browser html5 video" on so, and very quickly came up with html5 video with full cross browser compatibility. aside from that, try searching your favorite search engine for an answer to your problem. it is often useful to search for specific error messages if you have them — other developers will be likely to have had the same problems...
Testopia
ory, please report it to us so that we can fix most critical ones on time for testopia 3.0. do not ask when we plan to release 3.0, because we really don't know. "as soon as possible" is our best answer. testopia 2.5 this versions supports bugzilla 4.2 and 4.4, and the best news is that it no longer requires a patch for bugzilla. if you are upgrading, please reverse the existing version's patch before installing. a fresh install only requires that you untar the tarball in your bugzilla root directory and run checksetup. thanks go to lpsolit from the bugzilla team for his work in making this possible. testopia 2.4 this version supports bugzilla 3.6. important notice: if you are upgrading on a case sensitive filesystem you must remove the existing testopia folder in the extensions directory. ...
... filesystem you must remove the existing testopia folder in the extensions directory. if you have made modifications to the testopia source code, you will need to merge them into the new testopia folder (capital t). if you are on windows or another case insensitive file system you should first rename the folder (testopia-old for example) and then unzip the tarball. you can then merge your changes before deleting the old version. api users take note: positional parameters are now deprecated. all params should now be sent in a hash (struct, dict, hashmap or whatever your language of choice calls key, value pairs). though all attempts have been made to provide continuing support for positional parameters, please be aware that some api calls may fail until you make this change. also, future version...
...precated. all params should now be sent in a hash (struct, dict, hashmap or whatever your language of choice calls key, value pairs). though all attempts have been made to provide continuing support for positional parameters, please be aware that some api calls may fail until you make this change. also, future versions may remove this support completely. as always please backup your installation before attempting to install or upgrade. testopia 2.3 this version supports bugzilla 3.4. the main new features are: support xml export and import 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 ex...
Chrome registration
ion appversion<=version appversion>version appversion>=version indicates that the instruction should only be applied if the extension is installed into the application version identified. multiple appversion flags may be included on a single line, in which case the line is applied if any of the flags match. the version string must conform to the toolkit version format. note: versions of gecko before gecko 1.8.0.13 and gecko 1.8.1.5 contained a bug where if you use the comparisons <, > or =, the version string had be two or more characters long. if not, you would get a message in the error console that the appversion flag was not recognized. see bug 380398. platformversion when supporting more then one application, it is often more convenient for an extension to specify which gecko versio...
...s the following instructions are supported in bootstrapped extensions: manifest content locale skin override debugging a chrome manifest file the chrome list extension shows all registered chrome. ...
...is very helpful when trying to write a chrome.manifest file as you can inspect where the files are being mapped from (jar files, local directory, etc.) old-style contents.rdf manifests before the plaintext manifests were introduced (which happened in firefox 1.5, toolkit 1.8), rdf manifests named "contents.rdf" were used to register chrome. this format is deprecated; however, seamonkey versions before version 2 do not support the plaintext manifest format yet, so contents.rdf manifests are required for extensions that wish to maintain backwards compatibility with firefox 1.0 or the suite. gecko 1.9.2 note the contents.rdf manifest format is no longer supported at all starting with gecko 1.9.2; add-ons already installed using this format will continue to work but can no longer be installe...
Configuring Build Options
do not make substantive changes to this document without consulting benjamin smedberg <benjamin@smedbergs.us> or one of the build-config peersthis document details how to configure firefox builds. most of the time a mozconfig file is not required. the default options are the most well-supported, so it is preferable to add as few options as possible. please read the following directions carefully before building, and follow them in order. skipping any step may cause the build to fail, or the built software to be unusable. build options, including options not usable from the command-line, may appear in "confvars.sh" files in the source tree. using a mozconfig configuration file the choice of which mozilla application to build and other configuration options can be configured in a mozconfig file...
...ch the mozilla source. disabling these tests can speed build time and reduce disk space considerably. developers should generally not use this option. localization mk_add_options moz_co_locales=isocode tbd. ac_add_options --enable-ui-locale=isocode tbd. ac_add_options --with-l10n-base=/path/to/base/dir tbd. other options mk_add_options autoclobber=1 if a clobber would be required before a build, this will cause mach to clobber and continue with the build instead of asking the user to manually clobber and exiting. ac_add_options --disable-crypto cryptography is enabled by default. in some countries, it may be illegal to use or export cryptographic software. you should become familiar with the cryptography laws in your country. on the 1.7 and aviary branches, cryptography was o...
...nabling the crash reporter in your local build, you will need to run mach with the --enable-crash-reporter (note the extra dash) to enable it at runtime, like so: `./mach run --enable-crash-reporter` ac_add_options --enable-warnings-as-errors this makes compiler warnings into errors which fail the build. this can be useful since certain warnings coincide with reviewbot lints which must be fixed before merging. ac_add_options --with-ccache=/path/to/.mozbuild/sccache/sccache this enables sccache to speed up builds. this saves a considerable amount of time directly after a clobber build, so pulling in new updates and rebasing is less time-consuming. example mozconfig files mozilla's official builds use mozconfig files from the appropriate directory within each repository. warning: thes...
Simple Instantbird build
nection for the initial source download. setup: depending on your operating system you will need to carry out a different process to prepare your machine. so firstly complete the instructions for your os and then continue following these build instructions. windows build prerequisites gnu/linux build prerequisites mac os x build prerequisites tip: after completing setup for your os, and before you get the source, you can opt to add the progressextension to your mercurial.ini (for windows) or .hgrc (for *nix / mac) file. this will provide status feedback during the lengthy clone / download process. see: configure mercurial .hgrc file for progress extension. get the source note: on windows, you won't be able to build the instantbird source code if it's under a directory with spaces in ...
...s/purple if you've set up your build environment as above, then all you need to do is: echo 'ac_add_options --enable-extensions=purple' >> .mozconfig in the comm-central directory, or just add the ac_add_options --enable-extensions=purple line to your .mozconfig with your favorite editor. then just re-run the mach command above (you may need to clobber (see below), or you can do the addition before running make for the first time). running to run your build, you can use ./mozilla/mach run there are various command line parameters you can add, e.g. to specify a profile. various temporary files, libraries, and the instantbird executable will be found in your object directory (under comm-central/), which is prefixed with obj-. the exact name depends on your system and os. for example, a m...
... incremental builds when you are working on your own patches, an incremental build is often enough, and is very fast indeed. this will only rebuild a particular folder. so, for instantbird, you would run mach build im which has been configured to automatically rebuild /chat as well. upstream changes to fetch the latest upstream changes, in your comm-central directory, run the same command as before: python client.py checkout problems building? have you: tried a clobber? this means deleting the object directory so that your next build is completely fresh. to do this you can use mach clobber checked the instantbird buildbot for known failures at the time you pulled the code? if the trunk is broken, you may wish to consider building one of the branches (to pull the source co...
Eclipse CDT
dd 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 tools. since it's a pain to install them and keep them up to date we do not recommend getting eclipse this way.) increase eclipse's memory limits! make sure you do this! before you use eclipse with the mozilla source 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...
...rectory (for example, to take account of some changes that you yourself made) select "index > freshen all files" on that directory. to rebuild the entire index (for example when you pull from mozilla-central) select "index > rebuild" on the project root. usage tips below are some of the more useful user tips. (if you're thinking of adding tips, please first consider how widely useful they'll be before adding to this already lengthy page.) for further documentation see the official eclipse user guide and eclipse cdt user guide. keyboard shortcuts regarding key bindings (keyboard shortcuts), the bindings given below are the defaults. you can change the key bindings by opening the workspace preferences (eclipse > preferences, or window > preferences) and selecting "general > keys". you can set ...
..." issue. (update 2017-03-28: the option index all header variants has been added in version 8.3.0, as explained in a comment of the mentioned bug. this option allows to have multiple definitions for the same header file, which might fix this issue. update 2017-11-04 by jwatt: ticking the "index all header variants" option caused eclipse to blow through the 12 gb of ram i'd given it while indexing before it ran out of memory and crashed.) there are parser errors it is expected that eclipse will show parser errors even for a known-good copy of the mozilla source. parser errors/warnings are indicated by red/yellow markers on files in the project explorer tab, and in the gutter down the right-hand side of open source files. in the case of the latter you can click on the marker to jump to the probl...
Error codes returned by Mozilla APIs
mponents.results. for example, by using components.results.ns_error_not_initialized general errors the following errors are general and can occur when using any component. ns_error_not_initialized (0xc1f30001) an attempt was made to use a component or object which has not yet been initialized. these components usually provide an initialization method, often called init, which must be called before other methods are used. ns_error_already_initialized (0xc1f30002) an attempt is made to initialize a component or object again which has already been initialized. ns_error_not_implemented (0x80004001) this error is caused by methods which are not implemented. this could occur because the implementation has not yet been written, or because the component intentionally does not support the desir...
...le with a unique filename. this indicates that too many files have been created already. ns_error_file_no_device_space (0x80520010) ns_error_file_name_too_long (0x80520011) indicates that a file name or path is larger than the platform can handle. ns_error_file_not_found (0x80520012) an attempt was made to access a file that does not exist. use nsifile.exists() to check if the file exists beforehand. ns_error_file_read_only (0x80520013) an attempt was made to create or write to a file or directory that is read only. this might happen if the file is not writable, the directory containing the file is not writable or the disk is write protected. use nsifile.iswritable() to check if the file can be written to. ns_error_file_dir_not_empty (0x80520014) when calling nsifile.remove() on a di...
...x80530005) an invalid character was used in a tag or attribute name. ns_error_dom_no_data_allowed_err (0x80530006) ns_error_dom_no_modification_allowed_err (0x80530007) this error can occur when an attempt is made to modify an aspect of an object that cannot be changed. ns_error_dom_not_found_err (0x80530008) a node was not found. for example, an attempt was made to use the element.insertbefore method to insert a node before one that is not a child. ns_error_dom_not_supported_err (0x80530009) the operation is not supported. ns_error_dom_inuse_attribute_err (0x8053000a) ns_error_dom_invalid_state_err (0x8053000b) an attempt was made to use an object which is no longer usable. ns_error_dom_syntax_err (0x8053000c) an attribute value or property was set to an invalid value. ns_er...
Storage access policy: Block cookies from trackers
't yet plan to ship to release users; experimental features will not be included in this documentation, but may nevertheless impact the functionality of domains classified as trackers. we recommend sites test with firefox nightly, as this includes the newest version of our protections. as described above, note that nightly may include additional protections that end up getting removed or changed before they reach our release users. we’ll keep this page updated with the newest information as we strengthen our protections. these protections are on by default in nightly. the cookie policy can be enabled in other versions of firefox through the content blocking settings (these steps will vary by version; the linked documentation includes a dropdown to select the appropriate firefox version). re...
...mission on origins that have already been granted access. each time the heuristic is activated, or a success call to the storage access api is made, the pre-existing storage access expiration will be extended by 30 days, counting from the time the previous access was granted. please note that in the future we expect to make changes to how long storage access will remain valid for. as mentioned before, the way to know that you will be able to use storage as a third-party going forward will be using the storage access api. debugging we encourage site owners to test their sites, particularly those that rely on third-party content integrations. we’ve added several new features to firefox to make testing easier. developer tools notifications the network monitor in firefox developer tools now...
...social content provider that is classified as a tracker will not have access to their third-party cookies when the user first visits a new first party. thus, the user may appear logged out to the service despite being logged in when they visit the provider’s website directly. depending on the type of integration, the user may have to take some action to interact with the social content provider before the provider is given access to their cookies. for example: for social login, the user may have to click a login button on the first party. for social like or share buttons, the user will have to first interact with the button in a logged-out state. once they do, many social content providers will prompt them to log in. after these interactions, the provider will receive third-party storage...
Extending a Protocol
, pwindowglobal is in charge of contructing the parent/child relationship. without this, we can't send messages. anyway, let's put the above into practice by creating our custom protocol: pecho.ipdl. custom protocol - pecho.ipdl this next part requires us to both specify the protocol and actually implement everything in c++. it's quite involved and, unfortunately, all steps need to be done before we can successfully recompile. we will try to compile our code as we go, noting what we need to do along the way. to be sure, ipdl looks like a crazy mix of webidl, c++ header files, and es6. the syntax should hopefully be fairly obvious though. unfortunately, it's not really fully documented anywhere - and the ipdl parser gets easily confused (hence us excluding comments below). creating...
...tax is correct, and now we need to pwindowglobal.ipdl to manage our pecho protocol. updating pwindowglobal.ipdl open up ./dom/ipc/pwindowglobal.ipdl. we need to add the following things: at the top of the file: include protocol pecho; after "manager pbrowser or pinprocess;", add: manages pecho; finally, under parent: add async pecho(); - this is the "constructor" part we talked about before, which will allow us to eventually send messages. so roughly, it looks like this (things in bold is what we added). // stuff.. include protocol pecho; async protocol pwindowglobal { // stuff... manages pecho; child: // stuff... parent: async pecho(); // more stuff... } if the above additions are unclear, please see the final implementation of pecho as a diff in phabri...
...ild() = default; bool mactoralive; }; } // end of namespace dom } // end of namespace mozilla and add the echochild.h to dom/ipc/moz.build, as part of the exports.mozilla.dom array. again, remember that this must be in alphabetical order! compiling this will now complain: "fatal error: 'mozilla/dom/echoparent.h' file not found", so let's define echoparent.h. defining echoparent.h like before, create ./dom/ipc/echoparent.h, and code it as follows - the inline comments describe what's going on. note the recvecho(), we finally get to define where a message is received, yay!: #ifndef mozilla_dom_echoparent_h #define mozilla_dom_echoparent_h #include "mozilla/dom/pechoparent.h" namespace mozilla { namespace dom { class echoparent final : public pechoparent { friend class pechoparent...
Bootstrapping a new locale
ll the utility. clone the source code the next step is to download a copy of the source code to your local system, using mercurial. you will need to "hg clone" the existing release branch for mozilla so you have all the files locally for you to begin localization. make sure to have the directory where you intend to work as the current path on your terminal. (you should "cd" to the directory before beginning.) in the terminal, type the following command: $ hg clone http://hg.mozilla.org/releases/mozilla-x.x.x/ where "x.x.x" is the existing release branch version. for instance, for firefox 3.6, we use mozilla-1.9.2. refer to l10n:branches for the list of all branches. if you are interested in localizing thunderbird 3, seamonkey 2 or other mozilla projects based on gecko 1.9.1 you'll ne...
...) files into your localization. first, you should specify your locale's language identifier in ab-cd format, where "ab" is the iso 639 language code, and cd is the iso 3166 country code. the "-cd" part is only necessary to differentiate between versions of a language that are subtly different from country to country, such as in "en-us" and "en-gb" for united states english and british english. before you run the copy commands, you need to make the locale directory at the same level as the mozilla-1.9.x/ you just cloned from above. navigate to that level making sure you are *not* inside mozilla-1.9.x/ and then run the following commands. warning: don't copy and paste these commands; you need to replace "ab-cd" with your language identifier first and 1.9.x with the most current release branch...
...at order to proceed through translation. the localization phase lists (firefox 3.5: ff35.phaselist, firefox 3.6: ff36.phaselist). description of phases. land your translated files one by one, making sure it follows the *mozilla-1.9.2* structure. this will familiarize you with our "hg" commands and will get us something that we can import easily when you are done. working with bit bucket before a team becomes official, we like to get the localizers comfortable with the hg commands that allow for cloning, pulling, committing, and pushing work to an experimental repository. we use a web service called bit bucket to start the learning process. to begin, contact the l10n-drivers to let them know that you are interested in starting a localization. the l10n-drivers will help set up an expe...
Localizing without a specialized tool
ck or a binary file that is ready for installation. repeating the process allows a localizer to create a testable package to see his or her work as they progress to a final version. if you choose to localize mozilla with nothing more than a text editing application and not a specialized tool, this document (along with create a new localization) will enable you to learn just what needs to be done. before we start, did you make sure to install mercurial and confirm that you have set up the proper build environment on your local machine? you cannot begin localizing mozilla file by file without a specialized tool without going through the create a new localization page. what we will translate we will translate a small piece of the ui found in the search bar. the search bar is next to the right of t...
...ch engines...". to start, make sure you are in /path/to/your/working/directory/l10n-mozilla-1.9.2/x-testing and then, type the command mkdir /browser/chrome/browser now, step back out to the broader directory that contains both your l10n base (l10n-mozilla-1.9.2) and the en-us source code (mozilla-1.9.2). you can do this by typing: cd ../../ where each ".." represents the prior sub directory before the main directory where you want to be. you can always check the path by typing pwd once you are in the root working directory with both en-us source and the l10n base, copy the searchbar.dtd file by typing cp mozilla-1.9.2/browser/locales/chrome/browser/searchbar.dtd l10n-mozilla-1.9.2/x-testing/browser/chrome/browser/ open the file in your x-testing directory and translate the words inside t...
...'ll see, "add %s", where %s is replaced by the name of the site. again, to start, make sure you are in /path/to/your/working/directory/l10n-mozilla-1.9.2/x-testing now, step back out to the broader directory that contains both your l10n base (l10n-mozilla-1.9.2) and the en-us source code (mozilla-1.9.2). you can do this by typing: cd ../../ where each ".." represents the prior sub directory before the main directory where you want to be. you can always check the path by typing pwd once you are in the root working directory with both en-us source and the l10n base, copy the searchbar.dtd file by typing cp mozilla-1.9.2/browser/locales/chrome/browser/search.properties l10n-mozilla-1.9.2/x-testing/browser/chrome/browser/ open that file and translate the strings that follow the "=". for ins...
QA phase
this is due to a bug in the build logic. please either follow the above structure closely or adjust the commands below according to your custom setup. to copy this file to the appropriate directory, do the following: navigate to your working directory from your command-line terminal (i.e., where you created the folder structure described above). enter the following commands: ...
... test your localization. don't lose your work! your work is so important! we would really hate to see you lose any of it. after you test your localization, you should send it to a remote repository, which will serve as a backup for your work and will let others follow your progress. we're going to go through the process below. the official localization teams use repositories at hg.mozilla.org. before a team becomes official, we like to get the localizers comfortable with the hg commands that allow for cloning, pulling, committing, and pushing work to an experimental repository. we use a web service called bit bucket to start the learning process. note: you must have mercurial configured before you begin. that step is back on the initial setup page. if you haven't done that yet, don't worry,...
... cloning, pulling, committing, and pushing work to an experimental repository. we use a web service called bit bucket to start the learning process. note: you must have mercurial configured before you begin. that step is back on the initial setup page. if you haven't done that yet, don't worry, we'll wait for you! pushing to your repository there are a couple of things you should take note of before you push to your repository: make sure that your files have been encoded in unicode without bom (byte order mark). remember that here you are pushing an entire directory, not a .zip archive file or an .xpi lang pack. the instructions below will help you learn how to use your hg repository. after your new repository is created by the l10n-drivers, please visit the url for your repo. we'll...
Release phase
se to connet with your mercurial repository: http and ssh. be advised that there's an important distinction between them. you can pull using both, but you can only push through ssh. consequently, if you already have a local clone that you pulled using http, you'll need to modify a config file to tell mercurial to push through ssh. 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. add the following lines to your ~/.ssh/config file, replacing user@host.domain with your mozilla ldap account name: host hg.mozilla.org user user@host.domain if you have already cloned the remote repository using the http protocol using thi...
...hangesets will need to be pushed to the remote repository. the output will look something like this: comparing with ssh://hg.mozilla.org/releases/l10n-central/x-testing searching for changes changeset: 0:7c543e8f3a6a tag: tip user: your name <email@example.com> date: mon nov 23 18:08:25 2009 +0100 summary: added search bar strings make sure this output is accurate before continuing. once you've made sure the outgoing output is accurate, push this changeset to hg.mozilla.org by running the hg push command. mercurial will connect to the remote repository, authenticate through ssh and send the changesets. the output should look something like this: pushing to ssh://hg.mozilla.org/releases/l10n-central/x-testing searching for changes adding changesets adding manif...
...-to-release. only new l10n work is evaluated. this is done by generating a diff between the new release revision being considered and the previously approved release revision. focus is still on technical accuracy and completion of l10n work; not translation quality. release revisions are evaluated, not entire l10n repos. sign-offs do not need to be approved before revision merge between release channels, although it is recommended. there is a specific process to follow in bugzilla for requesting these reviews: file a bug requesting the review. attach your files to the bug. once attached, open the attachment details. in the attachment details, select the ? from the dropdown menu next to the review flag or the appropriate appr...
SVN for Localizers
eady installed cygwin but it didn't include the svn package, run the cygwin installer again and be sure to check the box beside subversion package. this option is found in the devel category. a possible alternative is to install tortoisesvn (graphical interface and command line client). note: if you do not already have access to svn, visit this wiki page on how to get set up with an svn account before proceeding. mozilla's svn repositories mozilla's svn server is publicly available at https://svn.mozilla.org. despite there being several directories at the root of the svn server, only the projects and mozillamessaging.com directories apply to web localizers. for this tutorial we'll use the mozilla.com project. here's the layout you will find within the projects/mozilla.com directory: navi...
... output with every change made to each file. it's a bit hard to read, but you can also create a diff file (aka a diff patch) use svn diff > /path/to/output/file.diff to save the output to a file. note that path/to/output is meant to indicate the directory on your computer where you wish to store the diff file. you can also run svn status to check the list of modified files (they'll display a m before the name) you're about to commit. once you're satisfied with changes, commit them to the appropriate mozilla svn repository by entering the following command: svn commit -m "minor modifications for firefox [version #] beta page for [your locale]" the svn commit command will commit your changes directly to the mozilla svn repositories. since you are writing to the repository here, you will ...
...e online. you will have the chance to see how the localized website will look when it's pushed to prod (i.e., a website that regular visitors will see). when localizing websites, l10n-drivers will always add needed files to your repository or update your files with new strings in english. it's very important for you to update your working copy with the newest files from mozilla svn repository before you start making changes. enter the following command from the command-line: svn update your local svn repository (i.e., working directory) will be updated with the newest files from the url you initially cloned your repository from. it's very important that you do this often. as a general rule, you should at least do it before translating anything. sometimes mistakes happen and you need t...
Creating localizable web applications
. _("continue to step 3") . "</a> &raquo;</b>", $locale_conf->url('/demo_create_3'));?></div> using &laquo; and &raquo; should be ok here for rtl languages (they are flipped correctly if there are no latin characters next to them, which there aren't any), so let's leave it as it is. in general though, we should consider implementing such decorations as css images (background-image or ::after's/::before's content) and then select them with "html[dir="rtl"] > ...". it a safer method. <?php if($showwearthis) { ?> $(".try-button").personasbutton({ 'haspersonas':'<span><?= _("wear this");?></span><span>&nbsp;</span>', 'hasfirefox':'<span><?= _("get personas now!");?></span><span>&nbsp;</span>', 'nofirefox':'<span><?= _("get personas with firefox");?></span><span>&nbsp;</span>' }); <...
...alent, with the "؟" character which is used in some rtl languages, like arabic and persian (note that hebrew uses "?"). you should then display the right icon depending on the locale. the following example shows how to achieve this with css. snippet 1. bad: <div class="tut_didyouknow"> <img src="/static/img/question-64.png" class="tut_icon"> <?printf (_("did you know you can test a persona before you submit it? <b><a href=\"%s\">find out how!</a>&raquo;</b>"), $locale_conf->url('/demo_create_3#test'));?> </div> snippet 2. good: css: div.tut_didyouknow { background: url(/static/img/question-64.png) no-repeat 0 0; padding-left: 64px; } html[dir='rtl'] div.tut_didyouknow { background-image: url(/static/img/question-64.png); background-position: 100% 0; padding-lef...
...</div> snippet 2. good: css: div.tut_didyouknow { background: url(/static/img/question-64.png) no-repeat 0 0; padding-left: 64px; } html[dir='rtl'] div.tut_didyouknow { background-image: url(/static/img/question-64.png); background-position: 100% 0; padding-left: 0; padding-right: 64px; } html/php: <div class="tut_didyouknow"> <?printf (_("did you know you can test a persona before you submit it? <b><a href=\"%s\">find out how!</a>&raquo;</b>"), $locale_conf->url('/demo_create_3#test'));?> </div> notice that the icon has been moved to css, so that it doesn't sit in a <img/> element. this is generally considered a good practice for decorative graphics. don't use images as buttons instead, use <button/> and style it with css. image 1. bad: snippet 1. good:...
Mozilla Development Strategies
it's easier to do it right once, when your mind is in the problem, than to do it once quickly and then have to come back and do it again the right way. the only thing worse than not understanding someone else's code is not understanding your own. test your code qa's job is to assure quality, not to add quality. that's your job. it's your responsibility to find and fix the problems in your code before checking in. when you land your bug-free code, it's qa's job to assure others that it's really bug free. make sure you appreciate anyone who finds a bug in your code. appreciate it even more if they find it before you ship. they're giving you a second chance to get it right before it becomes a bug that affects users. minimize how you are affected by regressions unless you are the type to go ou...
...long to review as a ten line patch, it usually takes much more time. if you can divide and conquer what you are working on into smaller chunks, you will find you'll get faster reviews. of course, not everything can be divided up. and, shorter fixes aren't necessarily better than longer ones. having parallel trees should allow you to work on other items while you are awaiting reviews. get advice before working on a patch or feature, instead of after if you are blocked, or stumped as to what to work on, talk to a lead sooner rather than later. most likely they will have a bug they can hand off to you, or they can help get you unblocked. since they are going to be reviewing your code later, run your plan of attack by them first. it's better to have an idea rejected, than a big patch. if you are...
...volved, solve it in person, on irc or over aim. a five minute discussion is worth an hour of e-mails. do thorough code reviews when you review someone else's code, review thoroughly. if another engineer checks in code that causes regressions or introduces bugs, you might be the one who has to fix it later. save yourself (and others) time later by doing a solid code review. review your own code before you ask for reviews practice your reviewing skills on your own patch before you seek reviews and a super review. better that you catch something, than the reviewers or super reviewers. you might find a problem, or find that you left in some dump() or printf() statements, or have messed up the whitespace. if you're working on something massive, start a branch if you are working on something big...
Gecko Profiler FAQ
ial string and then write a script that filters out all samples that were gathered after your marker. to increase the amount of data, you should run your automated gathering procedure many times, and then combine multiple profiles into one. we don’t have a script that combines profiles, but i can help you write one if you’re interested. in the end, you should have one big “before” profile and one big “after” profile. profile comparison is tricky. the only way that i’ve tried before is to use a “difference calltree”: in the regular call tree, each node of the calltree is assigned a weight which is just the number of samples that were under this call stack. in a difference call tree, each node’s weight instead is computed as <number of sample...
...that tree is then displayed in the usual way, with weights in decreasing order from top to bottom. then the call stacks whose cost increased the most in the “after” profile will be at the top, and those are the ones you usually want to look at if you caused a regression. ...
...[ehsan] this is similar to the previous question to some extent, but the specific answer really depends on what kind of compiler flag we’re talking about and what performance impact we’re interested to study. but the short answer is picking up real browser workloads, and finding ways to split out the overall cost contributed by the thing that your change is going to affect and compare things before and after. [mstange] this question is more about benchmarking than about profiling. if you want to measure things, please measure without the profiler running, because the profiler can add its own overhead. how do we find performance regressions caused by third-party and system addons, especially ones that only show up after extended uptime? by running into th...
Profiling with the Firefox Profiler
shes should be avoided if possible, as they can be quite expensive. keep your eyes out for flushes like this that are blocking the main thread for a long time. if you notice these things happening in a loop, that's a bug to be fixed, since we're likely "layout thrashing". some more tips and answers to common questions are available in a mid-2017 faq document. it's a good idea to search bugzilla before filing a bug about a performance problem in firefox but sometimes it's hard to find issues that have already been reported. therefore, it's usually a good idea to file a bug. profiling local windows builds if you built firefox for windows locally and you would like to use the local symbols with the profiler, you will need to run an additional tool; see profiling with the firefox profiler and lo...
...d list. description of all available environment variables may be printed by starting firefox with moz_profiler_help=1 set. if you want to profile firefox for android, you have to set this environment values by --es option of am command to launch firefox. this example is for firefox nightly (package name is org.mozilla.fennec_aurora), and you have to allow storage access on permission settings before launching it. adb shell am start -n org.mozilla.fennec_aurora/.app \ --es env0 moz_profiler_startup=1 \ --es env1 moz_profiler_shutdown=/sdcard/download/profiler.json then, if you select quit menu, you can collect profiling data to moz_profiler_shutdown file. profiling js benchmark (xpcshell) to profile the script run.js with ionmonkey (-i), type inference (-n) and jäegermonkey (-m). ...
...: the resulting "profile" will have the layer tree view enabled (but nothing else). this is useful in cases where you want to gain a quick visual understanding of a layer dump without having to take a profile. on b2g, each line of a layer dump in adb logcat output is prefixed with something like i/gecko (30593):. cleopatra doesn't currently understand this prefix, so it needs to be removed before pasting. display list dump the display list after each refresh with the texture data. this can be used to debug correctness problems. contribute source is located in tools/profiler. the bugzilla components are core::gecko profile for the profiler backend, and devtools::performance tools (profiler/timeline) for the toolbar button and about:profiling. the (now obsolete) profiler add-on rep...
Introduction to NSPR
r of native threads. global threads are scheduled by the host os--not by nspr--either within a process or across processes on the entire host. global threads correspond to native threads on the host os. nspr threads can also be either user threads or system threads. nspr provides a function, pr_cleanup, that synchronizes process termination. pr_cleanup waits for the last user thread to exit before returning, whereas it ignores system threads when determining when a process should exit. this arrangement implies that a system thread should not have volatile data that needs to be safely stored away. priorities for nspr threads are based loosely on hints provided by the client and sometimes constrained by the underlying operating system. therefore, priorities are not rigidly defined. for more...
...monitoring is about protecting data, not code. a monitored invariant is a boolean expression over the monitored data. the expression may be false only when a thread is in the monitor (holding the monitor's mutex). this requirement implies that when a thread first enters the monitor, an evaluation of the invariant expression must yield a true. the thread must also reinstate the monitored invariant before exiting the monitor. therefore, evaluation of the expression must also yield a true at that point in execution. a trivial example might be as follows. suppose an object has three values, v1, v2, and sum. the invariant is that the third value is the sum of the other two. expressed mathematically, the invariant is sum = v1 + v2. any modification of v1 or v2 requires modification of sum. since that...
...(monitor); return db; } the same function would be more appropriately written as follows: void *dequeue() { void *db; enter(monitor); while ((db = delink()) == null) wait(condition); exit(monitor); return db; } caution: the semantics of pr_waitcondvar assume that the monitor is about to be exited. this assumption implies that the monitored invariant must be reinstated before calling pr_waitcondvar. failure to do this will cause subtle but painful bugs. to modify monitored data safely, a thread must be in the monitor. since no other thread may modify or (in most cases) even observe the protected data from outside the monitor, the thread can safely make any modifications needed. when the changes have been completed, the thread notifies the condition associated with th...
PR_WaitCondVar
waits on a condition. syntax #include <prcvar.h> prstatus pr_waitcondvar( prcondvar *cvar, printervaltime timeout); parameters pr_waitcondvar has the following parameters: cvar the condition variable on which to wait. timeout the value pr_interval_no_timeout requires that a condition be notified (or the thread interrupted) before it will resume from the wait. the value pr_interval_no_wait causes the thread to release the lock, possibly causing a rescheduling within the runtime, then immediately attempt to reacquire the lock and resume. returns the function returns one of the following values: if successful, pr_success. if unsuccessful (for example, if the caller has not locked the lock associated with the condition variable or the thread was interrupted with pr_interrupt)...
...hin the runtime, then immediately attempt to reacquire the lock and resume. returns the function returns one of the following values: if successful, pr_success. if unsuccessful (for example, if the caller has not locked the lock associated with the condition variable or the thread was interrupted with pr_interrupt), pr_failure. the details can be determined with pr_geterror. description before the call to pr_waitcondvar, the lock associated with the condition variable must be held by the calling thread. after a call to pr_waitcondvar, the lock is released and the thread is blocked in a "waiting on condition" state until another thread notifies the condition or a caller-specified amount of time expires. when the condition variable is notified, a thread waiting on that condition moves f...
... ...
NSS PKCS11 Functions
r *pk11_getslotname(pk11slotinfo *slot); parameters this function has the following parameter: slot a pointer to a slot info structure. returns the function returns one of these values: if successful, a pointer to the name of the slot (a string). if unsuccessful, null. description if the slot is freed, the string with the slot name may also be freed. if you want to preserve it, copy the string before freeing the slot. do not try to free the string yourself. pk11_gettokenname gets the name of the token. syntax #include <pk11pub.h> char *pk11_gettokenname(pk11slotinfo *slot); parameters this function has the following parameter: slot a pointer to a slot info structure. returns the function returns one of these values: if successful, a pointer to the name of the token (a string). if unsucce...
...pk11_gettokenname(pk11slotinfo *slot); parameters this function has the following parameter: slot a pointer to a slot info structure. returns the function returns one of these values: if successful, a pointer to the name of the token (a string). if unsuccessful, null. description if the slot is freed, the string with the token name may also be freed. if you want to preserve it, copy the string before freeing the slot. do not try to free the string yourself. pk11_ishw finds out whether a slot is implemented in hardware or software. syntax #include <pk11pub.h> #include <prtypes.h> prbool pk11_ishw(pk11slotinfo *slot); parameters this function has the following parameter: slot a pointer to a slot info structure. returns the function returns one of these values: if the slot is implemented i...
...retry argument is pr_true, indicating that the password was tried and is wrong, the callback function should return null to indicate that it is unsuccessful, rather than attempting to return the same password again. failing to terminate when the retry argument is pr_true can result in an endless loop. several functions in the nss libraries use the password callback function to obtain the password before performing operations that involve the protected information. the third parameter to the password callback function is application-defined and can be used for any purpose. for example, mozilla uses the parameter to pass information about which window is associated with the modal dialog box requesting the password from the user. when nss ssl libraries call the password callback function, the value...
Python binding for NSS
me name as they appear in the c header files of nss/nspr. convenience functions are provided to translate between the numeric value of an enumerated constant and it's string representation and visa versa. python-nss internally supports utf-8. strings may be python str objects or python unicode objects. if a python unicode object is passed to a nss/nspr function it will be encoded as utf-8 first before being passed to nss/nspr. python-nss tries to be flexible when generating a print representation of complex objects. for simplicity you can receive a block of formatted text but if you need more control, such as when building gui elments you can access a list of "lines", each line is paired with an indentation level value. the (indent, text) pairs allow you to insert the item into a gui tree str...
...tting. deprecated elements of the python-nss api are marked with python deprecation warnings as well as being documented in the nss module documentation. as of python 2.7 deprecation warnings are no longer reported by default. it is suggested python developers using python-nss periodically run their code with deprecation warnings enabled. depercated elements will persist for a least two releases before being removed from the api entirely. project history red hat utilizes both nss and python in many of it's projects, however it was not previously possible to call nss directly from python. to solve this problem red hat generously funded the initial development of python-nss as well as it's continued maintenance. red hat following it's open source philosophy has contributed the source to the mo...
... threads will now yield during blocking io. socket.makefile() reimplemented file object methods that had been missing (readlines(), sendall(), and iteration) were implemented makefile now just returns the same socket object but increments an "open" ref count. thus a socket object behaves like a file object and must be closed once for each makefile() call before it's actually closed. sockets now support the iter protocol added methods: socket.readlines() socket.sendall() apply patches from miloslav trmač <mitr@redhat.com> for ref counting and threading support. thanks miloslav! review all ref counting, numerous ref counting fixes implement cyclic garba...
NSS_3.12.3_release_notes.html
yte count) sets the maximum number of bytes to read from the file named in the environment variable nsrandfile (see below). makes nsrandfile usable with /dev/urandom. nss_allow_weak_signature_alg boolean (any non-empty value to enable) enables the use of md2 and md4 hash algorithms inside signatures. this was allowed by default before nss 3.12.3. nss_hash_alg_support string specifies algorithms allowed to be used in certain applications, such as in signatures on certificates and crls. see documentation at this link. nss_strict_nofork string ("1", "disabled", or any other non-empty value) it is an ...
...port string specifies algorithms allowed to be used in certain applications, such as in signatures on certificates and crls. see documentation at this link. nss_strict_nofork string ("1", "disabled", or any other non-empty value) it is an error to try to use a pkcs#11 crypto module in a process before it has been initialized in that process, even if the module was initialized in the parent process. beginning in nss 3.12.3, softoken will detect this error. this environment variable controls softoken's response to that error. if set to to "1" or unset, softoken will trigger an assertion failure in debug builds, and will report an error in non-debug builds. ...
...sions. if set to any other non-empty value, softoken will report an error in both debug and non-debug builds. nss_use_decoded_cka_ec_point boolean (any non-empty value to enable) tells nss to send ec key points across the pkcs#11 interface in the non-standard unencoded format that was used by default before nss 3.12.3. the new key point format is a der encoded asn.1 octet string. nss_use_shexp_in_cert_name boolean (any non-empty value to enable) tells nss to allow shell-style wildcard patterns in certificates to match ssl server host names. this behavior was the default before nss 3.12.3. the new behavior conforms to rfc 2818. ...
Invariants
good reason whatsoever). if !js_isrunning(cx) && cx->globalobject == null, then cx->compartment == cx->runtime->defaultcompartment. while executing a script, cx->compartment == script->compartment. but this is true only so long as we are actually in the interpreter or jit code. a jsnative or other callback may move cx to another compartment, as long as it returns cx to the script's compartment before returning. a given trace-jit trace stays within a single compartment (indeed, a single global object) end-to-end. lifetime invariants in some places, pointers to jsobjects and jsstrings must refer to live heap objects, but this is not a hard fast rule, especially for strings. some jsstrings are allocated on the stack for quick operations. some commonly used strings are allocated statically; se...
...st refer to live heap objects, but this is not a hard fast rule, especially for strings. some jsstrings are allocated on the stack for quick operations. some commonly used strings are allocated statically; see jsstring::isstatic(). most jscontext pointers must point to live contexts, but jstitle::ownercx may point to one that has been destroyed! so code must check js_validcontextpointer(ownercx) before dereferencing it. shape invariants the shape guarantees hold whenever the property cache is enabled. also, we never change the shape of the global object on trace. (here "the global object" refers to the object at the end of the scope chain of the function object we're executing.) requests many functions require a request. that is, they take a parameter cx of type jscontext *, and require t...
...own 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, 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. jsop_bindname performs this lookup.) the rules below (not exactly invariants) govern the bytecode emitted for nameexpressions. background: the fastest instructions for nameexpressions are fat opcodes that combine a load with additional operations, as in jsop_inclocal or jsop_getlocalprop. failing that, jsop_{get,call,set}local and jsop_{get,call,set}arg are the fastest, followed by...
Property cache
ution of the same instruction. the jit reads the property cache too, as it needs the same information when recording such an instruction. if there is a cache miss, the jit performs parts 1 and 2 of the property access and fills the cache to avoid redoing that work in the interpreter. (in some cases this is necessary for correctness. when recording a getprop, the jit needs to know the result type before the interpreter executes the instruction. it is crucial that jit and interpreter get the same answer; possible pitfalls include native getters and resolve hooks. so the lookup must happen only once. the jit ensures this by using the property cache to forward its work to the interpreter.) for speed, the cache is a fixed-size hash table with no chaining. collisions simply cause old entries to be o...
...pe-regenerating gc occurred; then at t1 the lookup for p in x still finds the same property on x'. (informally: if another variable or property shadows x'.p, the shape of x' will change.) o this object is x, perhaps a call object. ↓ o ----> o a block object and its proto. ↓ o another call object. ↓ o ----> o ----> o ----> o ^global ^x' (----> indicates proto as before; downward arrows ↓ indicate the parent relation) method guarantee — if at time t0 the object x has shape s; and x has an own property p that is a method property (transparently joined function); and at time t1 an object y has shape s; and no shape-regenerating gc occurred; then at time t1 y's own property p is the same method property. (the existence of this property is guaranteed by th...
...re.) prototype change guarantee — if at time t0 the object x has shape s, and the object y has prototype z, and either x is y or x is on y's prototype chain, and at time t1 the object x has shape s, and no shape-regenerating gc occurred, then at t1 y has prototype z. (informally: changing an object's prototype changes its shape and the shape of every object that was on its prototype chain before the change. without this guarantee, every access to a property via a prototype chain would have to recheck each link in the prototype chain, even though assigning to __proto__ is very rare.) adding guarantee — if at time t0 the object x has shape s, and rt->protohazardshape is z, and x does not inherit a jsprop_shared or jsprop_readonly property with name n from any prototype, and at time...
Tracing JIT
o objects in the spidermonkey heap. the native code returns a pointer to a structure called a side exit. the monitor inspects the side exit and, depending on the exit condition, reconstructs a certain number of interpreter frames and flushes a certain set of writes back to the spidermonkey heap. frame reconstruction is necessary because a trace may inline a number of function calls, and may exit before those function calls return. write flushing is necessary because all writes to imported values in the native stack are deferred until trace-exit, as an optimization. if the side exit condition indicates that the trace exited successfully -- simply running out of native code or hitting a branch condition that no native code yet exists to handle -- the monitor will inspect the hit count for the tr...
...l record an alternative sub-trace beginning at the guard and patch the code into the existing guard. thereafter, when the guard fails it will jump to the specialized sub-trace. the term bail denotes "exiting a trace due to to a failed guard". when a guard bails, it means that there is no logic in the trace to handle the failed guard, and so the exit condition encodes the state of the interpreter before the guarded condition. the interpreter then re-executes the guarded condition, which will always succeed since the interpreter handles all outcomes of such a condition dynamically. the term deep bail denotes a special case of bailing: when a trace calls a native spidermonkey c function that gets part-way through executing and then forces a trace-exit (possibly due to a nested c function dependin...
...dermonkey c function that gets part-way through executing and then forces a trace-exit (possibly due to a nested c function depending on not-yet-flushed state in the trace). a deep bail is special only insofar as it requires flushing the full set of deferred writes in the trace if it occurs (and further, requires that all registers holding temporary trace operands have flushed to the native stack before execution). bailing from a regular guard involves executing precise per-guard write-flushing code, as the guard encodes a specific failed condition on a specific set of operands, and so the exit code can be much more fine-grained about and reconstructing the pre-bail state. a deep bail must be conservative because it is forced by the failure of an unknown condition elsewhere in native spidermonke...
TPS Tests
nd the whole test will fail as well. you can sign up for an fxa account on stage or dev by creating an fxa account after adding the identity.fxaccounts.autoconfig.uri preference (with the appropriate value) to about:config. additionally, note that the config file must parse as valid json, and so you can't have comments in it (sorry, i know this is annoying). one alternative is to put underscores before the "disabled" preferences, e.g. "_identity.fxaccounts.autoconfig.uri": "...". writing tps tests each tps test is run as a series of "phases". a phase runs in some firefox profile, and contains some set of actions to perform or check on that profile. phases have an n to m relationship with profiles, where n >= m (there can never be more phases than profiles). typically there are two profiles us...
...n asset lists; there are also some additional built-in functions. built-in functions sync(options) initiates a sync operation. if no options are passed, a default sync operation is performed. otherwise, a special sync can be performed if one of the following are passed: sync_wipe_server, sync_wipe_client, sync_reset_client. this will cause tps to set the firstsync pref to the relevant value before syncing, so that the described actionwill take place logger.loginfo(msg) logs the given message to the tps log. logger.asserttrue(condition, msg) asserts that condition is true, otherwise an exception is thrown and the test fails. logger.assertequal(val1, val2, msg) asserts that val1 is equal to val2, otherwise an exception is thrown and the test fails. custom functions you can also write...
...fter_first_modify], [sync] ]); phase('phase3', [ [sync], [bookmarks.verify, bookmarks_after_first_modify] ]); the effects of this test file will be: firefox is launched with profile1, the tps extension adds the two bookmarks specified in the bookmarks_initial array, then they are synced to the sync server. the sync_wipe_server argument causes tps to set the firstsync="wipeserver" pref before syncing, in case the sync account already contains data (this is typically unnecessary, and done largely as an example). firefox closes. firefox is launched with profile2, and all data is synced from the sync server. the tps extension verifies that all bookmarks in the bookmarks_initial list are present. then it modifies those bookmarks by applying the "changes" property to each of them. e.g., t...
Handling Mozilla Security Bugs
se (or plan to use) mozilla code in their own product offerings. some of these products may be used by large populations of end users, many of whom may not often upgrade or check for recent security fixes. we understand and acknowledge the concerns of those who believe that too-hasty disclosure of exploit details can provide a short-term advantage to potential attackers, who can exploit a problem before most end users become aware of its existence. 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. general ...
...h comments on the bug or the group mailing list, whether an immediate warning to users is appropriate and how it should be worded. the goals of this warning are: to inform mozilla users and testers of potential security risks in the versions they are using, and what can be done to mitigate those risks. to establish, for each bug, the amount of information a distributor can reveal immediately (before a fix is available) without putting other distributors and their customers at risk. a typical warning will mention the application or module affected, the affected versions, and a workaround (e.g., disabling javascript). if the group decides to publish a warning, the module owner, a peer, or some other person they may designate will post this message to the known vulnerabilities page (which wi...
...d choosing to report bugs through the standard bugzilla processes, the bug reporter is doing a positive service to the mozilla project; thus it makes sense that the bug reporter should be able to decide when the relevant bugzilla data should be made public. however, we will ask all individuals and organizations reporting security bugs through bugzilla to follow the voluntary guidelines below: before making a security bug world-readable, please provide a few days notice to the mozilla security bug group by sending an email to the private security bug group mailing list. please try not to keep bugs in the security-sensitive category for an unreasonably long amount of time. please try to be understanding and accommodating if a mozilla distributor has a legitimate need to keep a bug in the sec...
Accessing the Windows Registry Using XPCOM
en(wrk.root_key_local_machine, "software\\microsoft\\windows\\currentversion", wrk.access_read); var id = wrk.readstringvalue("productid"); wrk.close(); this example, while simple, shows several important things about using the interface. first, you must use createinstance() to get an object implementing this interface, not getservice(). second, you must call open() on the key before attempting to read a value. notice in the open() call that the root key to use is specified using the named constants available on the nsiwindowsregkey interface, in this case root_key_local_machine, which corresponds to hkey_local_machine in the windows registry. also notice that the path to the key has backslashes escaped, a necessity in javascript and c++ string constants. the desired access...
...m the interface, in this example access_read. this can be very important when dealing with non-administrator accounts with restricted privileges. the value is read using readstringvalue(). you have to specify what type of data you expect to read, which we will expand on later. finally, note that you should close the key when you are done to avoid wasting system resources. opening registry keys before doing anything with a registry key you must first open the key you are interested in. the example above demonstates this using the open() method. if you want to create a new key, you can use the create() method, which takes the same parameters as open(). note that it is not an error to call create() on an existing key, and doing so has the same result as calling open(). both of these methods tak...
...the nsiwindowsregkey interface provides methods for both of these—hasvalue() and haschild()—as demonstrated in this example: var wrk = components.classes["@mozilla.org/windows-registry-key;1"] .createinstance(components.interfaces.nsiwindowsregkey); wrk.open(wrk.root_key_loca...
Creating the Component Code
b lock user interface most of the actual work in the weblock component is preparing the component itself, finding the xpcom interfaces the component needs to use, and hooking into existing functionality within the gecko browser. component registration all xpcom components - whether they're stored in shared libraries (dlls, dsos, dylibs), javascript files, or otherwise - need to be registered before they can be used. registration is a process that happens in all xpcom applications, whether they're embedded gecko clients, mozilla, netscape 7, compuserve, or any other software that uses xpcom. registration provides the information that applications need in order to use components properly. the weblock component must do a number of things to register itself. specifically, the component library...
...l 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 forth. the interface used in this case is nsiclassinfo. starting from the outside in, onion peel view of xpcom component creation represents the sequence for constructing an xpcom object. onion peel view of xpcom component creation before we begin looking at the various parts of the component and how they'll be implemented in the source, let's look at the module in weblock.cpp to see where we're going. the source we're referring to is listed in its entirety at the end of this chapter (see weblock1.cpp). the source file for the weblock component contains three classes. in order to make the weblock component work in mozilla, you ha...
... #include <stdio.h> #define mozilla_strict_api #include "nsimodule.h" #include "nsifactory.h" #include "nsicomponentmanager.h" #include "nsicomponentregistrar.h" static const nsiid kimoduleiid = ns_...
Finishing the Component
the compiler itself changes its v-table layout, which can happen when the compiler changes its abi. for example, in 2002 the gnu compiler collection (gcc), version 3.2 changed the c++ abi, and this caused problems between libraries compiled with gcc 3.2 and applications compiled with an earlier version and vice versa. similar problems occurred with gcc 4.0, which underwent similar abi changes. before attempting to use unfrozen interfaces, you should contact the developers who are responsible for the code you're trying to use (i.e., module owners) and ask them how best to do what you are trying to do. be as precise you possibly can. they may be able to suggest a supported alternative, or they may be able to notify you about pending changes. the interface that we need for this project is somet...
... somewhere - as might be the case when the weblock component is used in a corporate intranet, for example - there are networking apis in gecko that will support this. or you could implement the web lock so that instead of blocking any site, the component would simply log all urls that are loaded. in any case, the process to make the xpcom component is the same. the method that handles the check before page loading and the only method we care about in our own implementation of nsicontentpolicy is shouldload(). the other method on the nsicontentpolicy interface is for blocking processing of specific elements in a document, but our policy is more restrictive: if the url isn't on the white list, the entire page should be blocked. in the weblock component, the shouldload method looks like this: ns...
...f uris of this kind are blocked, then gecko will not be able to start up, so we'll restrict the content policy to the http and ftp protocols. instead of extracting the string spec out of the nsiuri to do a string comparison, which would require you to do the parsing yourself, you can compare the nsiuri objects with each other, as in the following section. this ensures that the urls are canonical before they are compared. checking the white list the weblock implementation of the shouldload method starts by extracting the scheme of the incoming nsiuri. if the scheme isn't "http", "https", or "ftp", it immediately returns true, which continues the loading process unblocked. these three are the only kinds of uri that weblock will try to block. when it has one, it walks the linked list and create...
Introduction to XPCOM for the DOM
t, it has to decrease the reference count of that object by one. this is done using the "release" function, also defined in the nsisupports interface. when the reference count of an object hits 0 (zero), the object deletes itself. this is why it is very important to keep track of the reference count of each object. in the first case, if we forget to addref the object, the object may delete itself before we are done using the pointer, which would cause a crash when dereferencing it. in the second case, if we forget to release the object, it will never delete itself, which will cause "memory leaks", i.e. the memory is never returned because we keep the object around even if we don't need it. in both cases it's very bad, and we have to be extremely careful with the refcounting. fortunately, there ...
...ous example shows. at the beginning of this section, i talked about a second solution to get a pointer to an interface. this should be used in the case a getter function is not available. as you probably know, the "this" member of an object is a pointer to that object. you can thus simply cast "this" statically to the desired interface. you should however be absolutely sure of what you are doing before coding such a cast. it can lead to troubles with refcounting. here is a simple problem i encountered recently: in a member function of the nshtmlanchorelement class, i had to get a pointer to the nsicontent interface implemented by the nshtmlanchorelement object. however there is no such getter. i had to use the second solution: nscomptr<nsicontent> content = getter_addrefs(ns_static_cast(nsico...
...es for nsidomfabian. warning: in makefiles, there is a mix of tabs and whitespaces. make sure you copy exactly the other entries. then type "make" in dom/ to build the interface. if all goes well, a file nsidomfabian.h should be in dom/public/idl/html/_xpidlgen/, and it should contain the c++ code for our interface. from my own experience unfortunately it sometimes necessary to build "distclean" before it works. interface implementation let's take a closer look at how interfaces are implemented. we already know that an interface has to be implemented by a concrete c++ class. this class can implement multiple interfaces, directly or through inheritance (see the next section for a discussion of inheritance). we also saw that an interface defined in xpidl contains methods and attributes, which a...
nsIAccessibleText
tafteroffset(in long offset, in nsaccessibletextboundary boundarytype, out long startoffset, out long endoffset); astring gettextatoffset(in long offset, in nsaccessibletextboundary boundarytype, out long startoffset, out long endoffset); nsipersistentproperties gettextattributes(in boolean includedefattrs, in long offset, out long rangestartoffset, out long rangeendoffset); astring gettextbeforeoffset(in long offset, in nsaccessibletextboundary boundarytype, out long startoffset, out long endoffset); void removeselection(in long selectionnum); void scrollsubstringto(in long startindex, in long endindex, in unsigned long scrolltype); void scrollsubstringtopoint(in long startindex, in long endindex, in unsigned long coordinatetype, in long x, in long y); void setselectionbounds(i...
...olean includedefattrs, in long offset, out long rangestartoffset, out long rangeendoffset ); parameters includedefattrs points whether text attributes applied to the entire accessible should be included or not. offset text offset. rangestartoffset start offset of the range of text. rangeendoffset end offset of the range of text. ...
...estartoffset start offset of the range of text. rangeendoffset end offset of the range of text. return value exceptions thrown missing exception gettextbeforeoffset() string methods may need to return multibyte-encoded strings, since some locales can't be encoded using 16-bit chars. so this method might return utf-16 strings, or it could return "string" values which are utf-8. astring gettextbeforeoffset( in long offset, in nsaccessibletextboundary boundarytype, out long startoffset, out long endoffset ); parameters offset boundarytype startoffset endoffset return value removeselection() void removeselection( in long selectionnum ); parameters selectionnum scrollsubstringto() makes a specific part of string visible on screen. void scrollsubstringto( in long startinde...
nsIBrowserSearchService
orts last changed in gecko 2.0 (firefox 4 / thunderbird 3.3 / seamonkey 2.1) implemented by: @mozilla.org/browser/search-service;1. to access this service, use: var browsersearchservice = components.classes["@mozilla.org/browser/search-service;1"] .getservice(components.interfaces.nsibrowsersearchservice); attempting to use any method or attribute of this interface before init() has completed will force the service to fall back to a slower, synchronous, initialization. this is not an issue if your code is executed in reaction to a user interaction, as initialization is complete by then, but this is an issue if your code is executed during startup. if you need to write code that is executed during startup and makes use of nsibrowsersearchservice, you should make ...
...ype an integer representing the plugin file format. must be one of the supported search engine data types defined above. iconurl a url string to an icon file to be used as the search engine's icon. this value may be overridden by an icon specified in the engine description file. confirm a boolean value indicating whether the user should be asked for confirmation before this engine is added to the list. if this value is false, the engine will be added to the list upon successful load, but it will not be selected as the current engine. callback a nsisearchinstallcallback that will be notified when the addition is complete, or if the addition fails. it will not be called if addengine throws an exception. exceptions thrown ns_error_failure ...
...ray, size_is(enginecount)] out nsisearchengine engines ); parameters enginecount the number of hidden installed search engines. engines an array of the hidden installed nsisearchengines. init() initialize the service, or if the service is already initialized, do nothing. this method was introduced in firefox 16. attempting to call any method of this interface before init() has completed will force the service to fall back to a slower, synchronous, initialization. if your code requires nsibrowsersearchservice and is executed during startup, you should make sure that this code is executed from the callback to init(). void init( [optional] in nsibrowsersearchinitobserver observer ); parameters observer if specified, a callback called once i...
nsIChannel
tpchannel.cpp. method overview void asyncopen(in nsistreamlistener alistener, in nsisupports acontext); nsiinputstream open(); attributes attribute type description contentcharset acstring the character set of the channel's content if available and if applicable. this attribute only applies to textual data. setting contentcharset before the channel has been opened provides a hint to the channel on what the charset should be. the behavior is similar to contenttype. the value of the contentcharset attribute is a mixed case string. contentlength int64_t the length of the data associated with the channel if available. a value of -1 indicates that the content length is unknown. note: as of gecko 19.0...
...f that interface is exposed by the channel. contenttype acstring the mime type of the channel's content if available. note: the content type can often be wrongly specified (for example wrong file extension, wrong mime type, wrong document type stored on a server and so on.), and the caller most likely wants to verify with the actual data. setting contenttype before the channel has been opened provides a hint to the channel as to what the mime type is. the channel may ignore this hint in deciding on the actual mime type that it will report. setting contenttype after onstartrequest has been fired or after open() is called will override the type determined by the channel. setting contenttype between the time that asyncopen() is called and the time wh...
...stener's methods are called on the thread that calls asyncopen and are not called until after asyncopen returns. if asyncopen returns successfully, the channel promises to call at least onstartrequest and onstoprequest. if the nsirequest object passed to the stream listener's methods is not this channel, an appropriate onchannelredirect notification needs to be sent to the notification callbacks before onstartrequest is called. once onstartrequest is called, all following method calls on alistener will get the request that was passed to onstartrequest. if the channel's and loadgroup's notification callbacks do not provide an nsichanneleventsink when onchannelredirect would be called, that's equivalent to having called onchannelredirect. if asyncopen returns successfully, the channel is respon...
nsIHttpServer
* * @param callback * an asynchronous callback used to notify the user when this server is * stopped and all pending requests h...
...n use or because the process does * not have privileges to do so) * @note * behavior is undefined if this method is called after stop() has been * called on this but before the provided callback function has been * called. */ void start(in long port); /** * shuts down this server if it is running (including the period of time after * stop() has been called but before the provided callback has been called). * * @param callback * an asynchronous callback used to notify the user when this server is * stopped and all pending requests have been fully served * @throws ns_error_null_pointer * if callback is null * @throws ns_error_unexpected * if this server is not running */ void stop(in nsihttpserverstoppedcallback callback); ...
...for the lifetime of the server */ void registerfile(in string path, in nsifile file); /** * registers a custom path handler. ...
nsIMessenger
ring messageuri, in boolean savefirst, [optional] in boolean withoutwarning); parameters contenttype the content type of the attachment. url the url of the attachment. displayname the file name of the attachment. messageuri the url of the message containing the attachment. savefirst if true, the attachment is saved using saveattachment() before it is deleted. withoutwarning if true, no warning is shown to the user before the delete. detachallattachments() deletes a set of attachments. void detachallattachments(in unsigned long count, [array, size_is(count)] in string contenttypearray, [array, size_is(count)] in string urlarray, [array, size_is(count)...
...ng); parameters count the number of attachments to be deleted. contenttypearray an array of content types for each attachment. urlarray an array of urls for each attachment. displaynamearray an array of file names for each attachment. messageuriarray an array of urls for the message containing each attachment. savefirst if true, the attachments are saved using saveallattachments() before being deleted. withoutwarning if true, no warning is shown to the user before the delete. saveattachmenttofolder() saves an attachment in a given folder. saveattachmenttofolder() is used by the drag and drop code to drop an attachment to a destination folder. returns the actual file path (including the filename). nsilocalfile saveattachmenttofolder(in acstring , ...
...age or attachment to get the service for. return value the nsimsgmessageservice responsible for the url. msghdrfromuri() nsimsgdbhdr msghdrfromuri(in acstring auri); getmsguriatnavigatepos() gets the message a particular position in the navigation history. for example, back-forward history needs a list of visited messages, and where it is in the list. unfortunately, you must call this before navigating to a position, because calling this has the side effect of making us adjust our current history position, and not adding the loaded message to the history queue. acstring getmsguriatnavigatepos(in long apos); parameters apos the position to get the url from relative to the current history cursor. +1 is forward, -1 is back. return value the url at that point in the history.
nsIWebBrowser
n nsiweakreference alistener, in nsiidref aiid); attributes attribute type description containerwindow nsiwebbrowserchrome the chrome object associated with the browser instance. the embedder must create one chrome object for each browser object that is instantiated. the embedder must associate the two by setting this property to point to the chrome object before creating the browser window via the browser's nsibasewindow interface. the chrome object must also implement nsiembeddingsitewindow. the chrome may optionally implement nsiinterfacerequestor, nsiwebbrowserchromefocus, nsicontextmenulistener and nsitooltiplistener to receive additional notifications from the browser object. the chrome object may optionally implement nsiwebprogressliste...
...ng addwebbrowserlistener() and removewebbrowserlistener() to register a progress listener object. if the implementation does this, it must also implement nsiweakreference. note: the implementation should not refcount the supplied chrome object; it should assume that a non nsnull value is always valid. the embedder must explicitly set this value back to nsnull if the chrome object is destroyed before the browser object. note: nsiinterfacerequestor and nsiweakreference might also need to be implemented by the chrome object. contentdomwindow nsidomwindow the top-level dom window. the embedder may walk the entire dom starting from this value. read only. isactive boolean indicates whether this web browser is active. active means that it's visible enough that we ...
...ded. note: if this attribute is set to an object that implements nsisupportsweakreference, the implementation should get the nsiweakreference and hold that. otherwise, the implementation should not refcount this interface; it should assume that a non null value is always valid. in that case, the embedder should explicitly set this value back to null if the parent content listener is destroyed before the browser object. methods addwebbrowserlistener() registers a listener of the type specified by the iid to receive callbacks. the browser stores a weak reference to the listener to avoid any circular dependencies. typically this method will be called to register an object to receive nsiwebprogresslistener or nsishistorylistener notifications in which case the the iid is that of the interf...
nsIXPConnect
appen on a new temporary context. sandbox the sandbox object to evaluate the script in. returnstringonly the only results to come out of the computation (including exceptions) will be coerced into strings created in the sandbox. return value the result of the evaluation as a jsval. if the caller intends to use the return value from this call, the caller is responsible for rooting the jsval before making a call to this method. exceptions thrown missing exception missing description flagsystemfilenameprefix() preconfigure xpcnativewrapper automation so that when a scripted caller whose filename starts with filenameprefix accesses a wrapped native that is not flagged as "system", the wrapped native will be automatically wrapped with an xpcnativewrapper. void flagsystemfilenameprefix...
...tions thrown missing exception missing description wrapnative() wrapnative() will create a new jsobject or return an existing one. the jsobject is returned inside a refcounted nsixpconnectjsobjectholder. as long as this holder is held the jsobject will be protected from collection by javascript's garbage collector. it is a good idea to transfer the jsobject to some equally protected place before releasing the holder (i.e., use js_setproperty to make this object a property of some other jsobject). this method now correctly deals with cases where the passed in xpcom object already has an associated jsobject for the cases: 1) the xpcom object has already been wrapped for use in the same scope as an nsixpconnectwrappednative. 2) the xpcom object is in fact an nsixpconnectwrappedjs and thus ...
...lements nsiscriptobjectowner; i.e., is an idlc style dom object for which we can call getscriptobject to get the jsobject it uses to represent itself into javascript. it *might* be possible to queryinterface the nsixpconnectjsobjectholder returned by the method into an nsixpconnectwrappednative or an nsixpconnectwrappedjs. this method will never wrap the jsobject involved in an xpcnativewrapper before returning. returns: success: ns_ok failure: ns_error_xpc_bad_convert_native ns_error_xpc_cant_get_jsobject_of_dom_object ns_error_failure. nsixpconnectjsobjectholder wrapnative( in jscontextptr ajscontext, in jsobjectptr ascope, in nsisupports acomobj, in nsiidref aiid ); parameters ajscontext missing description ascope missing description acomobj missing description aiid mi...
Storage
tionality. this can result in significantly higher overhead file operation. closing a connection to close a connection on which only synchronous transactions were performed, use the mozistorageconnection.close() method. if you performed any asynchronous transactions, you should instead use the mozistorageconnection.asyncclose() method. the latter will allow all ongoing transactions to complete before closing the connection, and will optionally notify you via callback when the connection is closed. statements this section demonstrates how you can execute sql statements on your database. for a complete reference see mozistoragestatement. creating a statement there are actually two ways to execute a statement. you should choose the right one based on your needs. no results to be returned i...
...dparams(bp); } stmt.bindparameters(params); you can attach multiple sets of bindings to a statement by adding multiple mozistoragebindingparams objects to the array of parameter lists, adding each one through calls to the mozistoragebindingparamsarray.addparams(). once all the parameters are set up, a single call to mozistoragestatement.bindparameters() will ensure that the parameters are bound before execution. you can then execute the statement asynchronously, 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 s...
...mozistoragestatement.reset(). resetting a statement when you execute a statement synchronously, it is important to make sure you reset your statement. you can accomplish this by calling mozistoragestatement.reset() on the statement. if you end up finalizing the statement (see mozistoragestatement.finalize()) you do not need to worry about calling mozistoragestatement.reset(). you should do this before you reuse the statement. warning: if you fail to reset a write statement, it will continue to hold a lock on the database preventing future writes or reads. additionally, if you fail to reset a read statement, it will prevent any future writes to the database. in javascript, the language makes it pretty easy to ensure that you always reset a statement. be aware that you should always rese...
Reference Manual
if you're trying to fix a broken build, the faq might lead you to the answer more quickly. the basics design an nscomptr is designed to be a complete replacement for raw xpcom interface pointers where they are used as owning references. almost any place you could use a raw xpcom interface pointer, you should be able to use an nscomptr. an nscomptr is the exact same size and shape as a raw xpcom interface pointer. it can be used as a member variable without introducing bloat. ...
...rn expressed as a for loop, as well. consider, however, what would happen if you were trying to do this with a raw xpcom interface pointer. // iterating with raw xpcom interface pointers... nsidomnode* p = ...; while ( p ) { // ... p->getnext(&p); // trouble! we overwrote |p| without |release|ing it. } oops! we just failed to release p before putting a new pointer into it. people do this a lot, and it turns out to be a big source of leaks in normal xpcom code. well, could we do this instead? // iterating with raw xpcom interface pointers... nsidomnode* p = ...; while ( p ) { // ... ns_release(p); p->getnext(&p); // trouble! we tried to call a member function of a pointer // that ma...
...n the same thing with nscomptr. // iterating with |nscomptr|s... nscomptr<nsidomnode> p = ...; while ( p ) { // ... p->getnext( getter_addrefs(p) ); // trouble! we tried to call a member function through a |null| pointer. } using nscomptr is exactly like using raw xpcom interface pointers, here. getter_addrefs releases and clears out p before you assign into it, i.e., before getnext is called. which means that by the time we get around to calling getnext, we are trying to call it through a null pointer. unlike raw xpcom interface pointers, nscomptr will fire an assert instead of blindly trying to call getnext through a null pointer. that's the problem. so what's the solution? if this were raw xpcom interface pointers, we'd probably in...
Thunderbird Configuration Files
d know about: userchrome.css used to change the appearance of the browser. usercontent.css used to change the appearance of web pages. user.js used to change various preferences. all these files are plain text files you need to create in your profile folder and can be edited using a standard text editor, such as notepad on windows and gedit or kate on linux. locate your profile folder before the configuration files are presented, you should know how to find your profile folder, which is where thunderbird saves all your settings on your hard drive. on windows vista/xp/2000, the path is usually %appdata%\thunderbird\profiles\xxxxxxxx.default\, where xxxxxxxx is a random string of 8 characters. just browse to c:\documents and settings\[user name]\application data\thunderbird\profiles...
...efault profile that is automatically created when you start thunderbird for the first time. you can manage any number of profiles by using the profile manager. userchrome.css this file sets the display rules for various elements in the thunderbird user interface and is located in the sub-folder called chrome in your profile folder. this folder does not exist by default, so you need to create it before you can start adding your preferences. usercontent.css this file sets the display rules for web content and is located in the sub-folder called chrome in your profile folder. as with userchrome.css, this folder does not exist by default, so you need to create it before you can start adding your preferences. user.js this is the additional preferences file for thunderbird and is located in your...
...isplay rules for web content and is located in the sub-folder called chrome in your profile folder. as with userchrome.css, this folder does not exist by default, so you need to create it before you can start adding your preferences. user.js this is the additional preferences file for thunderbird and is located in your profile folder. the file does not exist by default, so you need to create it before you can start adding your preferences. in almost all cases, edits made using the user.js can be done via the config editor, which is the recommended method. windows users: if you know how to create a file, just skip this section. before you can create the file, you must make sure that you can see the file type extensions in windows. start explorer (just click on the my computer icon on your desk...
Initialization and Destruction - Plugins
the last instance of a plug-in is deleted, the plug-in code is unloaded from memory and the browser calls the function np_shutdown. plug-ins consume no resources, other than disk space, if not referenced. this chapter ends with initialize and shutdown example, which includes the np_initialize and np_shutdown methods. initialization the browser calls np_initialize when a plug-in is loaded and before the first instance is created. use this function to allocate the memory and resources shared by all instances of your plug-in. nperror np_initialize(void) { }; after the last plug-in instance is deleted, the browser calls np_shutdown, which releases the memory or resources allocated by np_initialize. for an example that shows the use of both the np_initialize and np_shutdown methods, see init...
...n unix, and powerpc shared library files or 68k code resources on mac os. to reduce memory overhead, plug-ins are usually loaded only when needed and released as soon as possible. in the initialization process, the browser passes the plug-in two tables of function pointers for all api calls: one table lists all api calls from the plug-in to the browser. this table is filled out by the browser before the initialization call. the other table lists all api calls from the browser to the plug-in. this table is filled out by the plug-in during the initialization call. the function tables also contain version information that the plug-in checks to verify that it is compatible with the api capabilities provided by the application. to check this information, use npn_version. no plug-in api calls ...
...nction, which informs the plug-in that its library is about to be unloaded, and gives it a chance to cancel any outstanding i/o requests, delete threads it created, free any memory it allocated, and perform any other closing tasks. the np_shutdown function releases memory or resources shared across all instances of a plug-in. it is called once after the last instance of the plug-in is destroyed, before releasing the plug-in library itself. void np_shutdown(void); for an example that shows both the np_initialize and np_shutdown methods, see initialize and shutdown example. initialize and shutdown example this example demonstrates the use of the np_initialize and np_shutdown methods. /* define global variable to hold the user agent string. */ static char* useragent = null; /* initialize fun...
Index - Firefox Developer Tools
uring tool you can measure a specific area of a web page. 37 memory devtools, firefox, mozilla, tools the memory tool lets you take a snapshot of the current tab's memory heap. it then provides a number of views of the heap that can show you which objects account for memory usage and exactly where in your code you are allocating memory. 38 aggregate view before firefox 48, this was the default view of a heap snapshot. after firefox 48, the default view is the tree map view, and you can switch to the aggregate view using the dropdown labeled "view:": 39 basic operations before firefox 50, the memory tool is not enabled by default. to enable it, open the developer tool settings, and check the "memory" box under "default firefox devel...
...nce. with the performance tool you create a recording, or profile, of your site over a period of time. the tool then shows you an overview of the things the browser was doing to render your site over the profile, and a graph of the frame rate over the profile. 83 allocations to enable the allocations view, you must check "record allocations" in the performance tool settings, before recording a profile. then record a profile as usual, and you will see a new tab labeled "allocations" in the toolbar: 84 call tree javascript, performance, memory the call tree is a sampling profiler. it periodically samples the state of the javascript engine and records the stack for the code executing at the time. statistically, the number of samples taken in which we were ...
...oper tools at a specific iframe within a document. 157 about:debugging debugger, remote debugging, about:debugging the about:debugging page provides a single place from which you can attach the firefox developer tools to a number of debugging targets. at the moment it supports three main sorts of targets: restartless add-ons, tabs, and workers. 158 about:debugging (before firefox 68) the about:debugging page provides a single place from which you can attach the firefox developer tools to a number of debugging targets. at the moment it supports three main sorts of targets: restartless add-ons, tabs, and workers. ...
Aggregate view - Firefox Developer Tools
after firefox 48, the default view is the tree map view, and you can switch to the aggregate view using the dropdown labeled "view:": the aggregate view looks something like this: it presents a breakdown of the heap's contents, as a table. there are three main ways to group the data: type call stack inverted call stack you can switch between them using the dropdown menu labeled "group by:" located at the top of the panel: there's also a box labeled "filter" at the top-right of the pane. you can use this to filter the contents of the snapshot that are displayed, so you can quickly see, for example, how many objects of a specific class were allocated. ...
...f 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 shows you exactly where in your code you are making heap allocations. because tracing allocations has a runtime cost, it must be explicitly enabled by checking "record call stacks" before you allocate the memory in the snapshot. you'll then see a list of all the functions that allocated objects, ordered by the size of the allocations they made: the structure of this view is very much like the structure of the call tree, only it shows allocations rather than processor samples. so, for example, the first entry says that: 4,832,592 bytes, comprising 93% of the total heap usa...
...ng for 89% of the heap usage in our page. (no stack available) in the example above you'll note that 7% of the heap is marked "(no stack available)". this is because not all heap usage results from your javascript. for example: any scripts the page loads occupy heap space sometimes an object is allocated when there is no javascript on the stack. for example, dom event objects are allocated before the javascript is run and event handlers are called. many real-world pages will have a much higher "(no stack available)" share than 7%. ...
Examine and edit HTML - Firefox Developer Tools
r display: inline flex applied to it. clicking the marker enables the flexbox highlighter. custom… the element is a custom element. clicking the marker switches to the line of javascript code in the debugger where the custom element got defined. note: there are some useful keyboard shortcuts that can be used in the html tree — see the html pane keyboard shortcuts list. ::before and ::after you can inspect pseudo-elements added using ::before and ::after: custom element definition when you open the inspector on a page that includes custom elements, you can view the class definition for the custom element in the debugger: inspect the element click on the word custom the source for the element's class will be displayed in the debugger. whitespace-only text ...
... context menu reference edit as html ...
...e disclosure triangle next to an element. collapse in the tree view, collapse the current element. this is equivalent to clicking the disclosure arrow next to an element that's expanded. (paste) inner html paste the clipboard contents into the node as its innerhtml. (paste) outer html paste the clipboard contents into the node as its outerhtml. (paste) before paste the clipboard contents into the document immediately before this node. (paste) after paste the clipboard contents into the document immediately after this node. (paste) as first child paste the clipboard contents into the document as the first child of this node. (paste) as last child paste the clipboard contents into the document as the last child of ...
about:debugging - Firefox Developer Tools
installed in firefox, the tabs that you currently have open, and service workers running on firefox. if your about:debugging page is different from the one displayed here, go to about:config, find and set the option devtools.aboutdebugging.new-enabled to true. setup tab connecting to a remote device firefox supports debugging over usb with android devices, using the about:debugging page. before you connect: enable developer settings on your android device. enable usb debugging in the android developer settings. enable remote debugging via usb in the advanced settings in firefox on the android device. connect the android device to your computer using a usb cable. if your device doesn't appear in the lefthand side of the about:debugging page, try clicking the refresh devices butto...
... try clicking the refresh devices button. if it still doesn't appear, it may be because the link between your android device and your computer is not authorized yet. first make sure you have installed android debug bridge from android tools on your computer in order for it to be able to connect to your device. next, disable every debugging setting already activated and repeat the steps described before. your device should show a popup to authorize your computer to connect to it — accept this and then click the refresh devices button again. the device should appear. note: you do not need to install the full android studio sdk. only adb is needed. to start a debugging session, first open the page that you wish to debug and then click connect next to the device name to open a connection to i...
...eference is set to true. extensions loading a temporary extension with the load temporary add-on button you can temporarily load a web extension from a directory on disk. click the button, navigate to the directory containing the add-on and select its manifest file. the temporary extension is then displayed under the temporary extensions header. you don't have to package or sign the extension before loading it, and it stays installed until you restart 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...
Basic animations - Web APIs
« previousnext » since we're using javascript to control <canvas> elements, it's also very easy to make (interactive) animations. in this chapter we will take a look at how to do some basic animations. probably the biggest limitation is, that once a shape gets drawn, it stays that way. if we need to move it we have to redraw it and everything that was drawn before it. it takes a lot of time to redraw complex frames and the performance depends highly on the speed of the computer it's running on. basic animation steps these are the steps you need to take to draw a frame: clear the canvas unless the shapes you'll be drawing fill the complete canvas (for instance a backdrop image), you need to clear any shapes that have been drawn previously. the easiest way to do this is...
...earrect() method. save the canvas state if you're changing any setting (such as styles, transformations, etc.) which affect the canvas state and you want to make sure the original state is used each time a frame is drawn, you need to save that original state. draw animated shapes the step where you do the actual frame rendering. restore the canvas state if you've saved the state, restore it before drawing a new frame. controlling an animation shapes are drawn to the canvas by using the canvas methods directly or by calling custom functions. in normal circumstances, we only see these results appear on the canvas when the script finishes executing. for instance, it isn't possible to do an animation from within a for loop. that means we need a way to execute our drawing functions over a p...
...od of time. setinterval(function, delay) starts repeatedly executing the function specified by function every delay milliseconds. settimeout(function, delay) executes the function specified by function in delay milliseconds. requestanimationframe(callback) tells the browser that you wish to perform an animation and requests that the browser call a specified function to update an animation before the next repaint. if you don't want any user interaction you can use the setinterval() function which repeatedly executes the supplied code. if we wanted to make a game, we could use keyboard or mouse events to control the animation and use settimeout(). by setting eventlisteners, we catch any user interaction and execute our animation functions. in the examples below, we'll use the window.re...
Transformations - Web APIs
« previousnext » earlier in this tutorial we've learned about the canvas grid and the coordinate space. until now, we only used the default grid and changed the size of the overall canvas for our needs. with transformations there are more powerful ways to translate the origin to a different position, rotate the grid and even scale it. saving and restoring state before we look at the transformation methods, let's look at two other methods which are indispensable once you start 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 o...
...emoved from the stack, and settings are restored. if we hadn't saved the state using save(), we would need to change the fill color and transparency manually in order to return to the previous state. this would be easy for two properties, but if we have more than that, our code would become very long, very fast. when the second restore() statement is called, the original state (the one we set up before the first call to save) is restored and the last rectangle is once again drawn in black. screenshotlive sample translating the first of the transformation methods we'll look at is translate(). this method is used to move the canvas and its origin to a different point in the grid. translate(x, y) moves the canvas and its origin on the grid. x indicates the horizontal distance to move, and y...
...creenshotlive sample translating the first of the transformation methods we'll look at is translate(). this method is used to move the canvas and its origin to a different point in the grid. translate(x, y) moves the canvas and its origin on the grid. x indicates the horizontal distance to move, and y indicates how far to move the grid vertically. it's a good idea to save the canvas state before doing any transformations. in most cases, it is just easier to call the restore method than having to do a reverse translation to return to the original state. also if you're translating inside a loop and don't save and restore the canvas state, you might end up missing part of your drawing, because it was drawn outside the canvas edge. a translate example this example demonstrates some of the ...
ChildNode.after() - Web APIs
Web › API › ChildNode › after
e, writable: true, value: function after() { var argarr = array.prototype.slice.call(arguments), docfrag = document.createdocumentfragment(); argarr.foreach(function (argitem) { var isnode = argitem instanceof node; docfrag.appendchild(isnode ? ...
...gani/js-polyfill_element.prototype.after/blob/master/after.js (function(x){ var o=x.prototype,p='after'; if(!o[p]){ o[p]=function(){ var e, m=arguments, l=m.length, i=0, t=this, p=t.parentnode, n=node, s=string, d=document; if(p!==null){ while(i<l){ e=m[i]; if(e instanceof n){ t=t.nextsibling; if(t!==null){ p.insertbefore(e,t); }else{ p.appendchild(e); }; }else{ p.appendchild(d.createtextnode(s(e))); }; ++i; }; }; }; }; })(element); /* minified: (function(x){ var o=x.prototype; o.after||(o.after=function(){var e,m=arguments,l=m.length,i=0,t=this,p=t.parentnode,n=node,s=string,d=document;if(p!==null){while(i<l){((...
... living standard initial definition. ...
Document.createElement() - Web APIs
t 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. examples basic e...
...rome, 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. examples basic example this creates a new <div> and inserts it before the element with the id "div1". html <!doctype html> <html> <head> <title>||working with elements||</title> </head> <body> <div id="div1">the text above has been created dynamically.</div> </body> </html> javascript document.body.onload = addelement; function addelement () { // create a new div element const newdiv = document.createelement("div"); // and give it some content co...
...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 ...
Element.scrollHeight - Web APIs
n due to overflow. 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. if the element's content can fit without a need for vertical scrollbar, its scrollheight is equal to clientheight this property will round the value to an integer. if you need a fractional value, use element.getboundingclientrect(). syntax elemscrollheight = element.scrollheight; value an integer corresponding to the scrollheight pixel value of the element. example padding-...
... working draft initial definition ...
... working draft initial definition ...
Comparison of Event Targets - Web APIs
t whose eventlisteners are currently being processed. as the event capturing and bubbling occurs, this value changes. event.relatedtarget dom mouseevent interface identifies a secondary target for the event. event.explicitoriginaltarget event.webidl 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), and in that case .target will show the parent and .explicitoriginaltarget will show the text node. unlike .originaltarget, .explicitoriginaltarget will never contain anonymous content. event.originaltarget event.webidl the original target of the...
...argeting occurs. for example, mouse events are retargeted to their parent node when they happen over text nodes (bug 185889), and in that case .target will show the parent and .explicitoriginaltarget will show the text node. unlike .originaltarget, .explicitoriginaltarget will never contain anonymous content. event.originaltarget event.webidl the original target of the event, before any retargetings. see anonymous content#event_flow_and_targeting for details. event.composedtarget event.webidl the original non-native target of the event before composition from shadow dom. use of explicitoriginaltarget and originaltarget todo: only available in a mozilla-based browser? todo: only suitable for extension-developers? examples <!doctype html> <html>...
... <td class="standard">target who's event listener is being processed <small>event.currenttarget</small></td> <td class="standard">identify other element (if any) involved in the event <small>event.relatedtarget</small></td> <td class="non-standard">if there was a retargetting of the event for some reason <small> event.explicitoriginaltarget</small> contains the target before retargetting (never contains anonymous targets)</td> <td class="non-standard">if there was a retargetting of the event for some reason <small> event.originaltarget</small> contains the target before retargetting (may contain anonymous targets)</td> </tr> </thead> <tr> <td id="target"></td> <td id="currenttarget"></td> <td id="relatedtarget"></td...
Event.initEvent() - Web APIs
Web › API › Event › initEvent
once dispatched, it doesn't do anything anymore. do not use this method anymore as it is deprecated. instead use specific event constructors, like event(). ...
...ox for androidopera for androidsafari on iossamsung internetinitevent deprecatedchrome full support yesedge full support 12firefox full support 17 full support 17 no support ? ...
... full support yeswebview android full support yeschrome android full support yesfirefox android full support 17 full support 17 no support ? ...
HTMLBodyElement - Web APIs
ited links. methods no specific methods; inherits methods from its parent, htmlelement, and from windoweventhandlers. event handlers no specific event handlers; inherits event handlers from its parent, htmlelement and from windoweventhandlers. windoweventhandlers.onafterprint is an eventhandler representing the code to be called when the afterprint event is raised. windoweventhandlers.onbeforeprint is an eventhandler representing the code to be called when the beforeprint event is raised. windoweventhandlers.onbeforeunload is an eventhandler representing the code to be called when the beforeunload event is raised. windoweventhandlers.onhashchange is an eventhandler representing the code to be called when the hashchange event is raised. windoweventhandlers.onlanguagechange is a...
...ise was rejected but the rejection was not handled. windoweventhandlers.onunload is an eventhandler representing the code to be called when the unload event is raised. specifications specification status comment html living standardthe definition of 'htmlbodyelement' in that specification. living standard technically, the event-related properties onafterprint, onbeforeprint, onbeforeunload, onblur, onerror, onfocus, onhashchange, 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' i...
...andlers. htmlbodyelement implements this interface. html 5.1the definition of 'htmlbodyelement' in that specification. recommendation html5the definition of 'htmlbodyelement' in that specification. recommendation the following properties are now obsolete: alink, bgcolor, background, link, text, and vlink. the following properties have been added: onafterprint, onbeforeprint, onbeforeunload, onblur, onerror, onfocus, onhashchange, onload, onmessage, onoffline, ononline, onpopstate, onresize, onstorage, and onunload. document object model (dom) level 2 html specificationthe definition of 'htmlbodyelement' in that specification. obsolete no change from document object model (dom) level 1 specification. document object model (dom) level 1 sp...
In depth: Microtasks and the JavaScript runtime environment - Web APIs
ss multiple agents—each component of an agent is unique to that agent. here we look at how the runtime functions in slightly more detail. event loops each agent is driven by an event loop, which collects any user and other events, enqueuing tasks to handle each callback. it then runs any pending javascript tasks, then any pending microtasks, then performs any needed rendering and painting before looping again to check for pending tasks. your web site or app's code runs in the same thread, sharing the same event loop, as the user interface of the web browser itself. this is the main thread, and in addition to running your site's main code body, it handles receiving and dispatching user and other events, rendering and painting web content, and so forth. the event loop, then, drives every...
... will not run until the next iteration. each time a task exits, and the execution context stack is empty, each microtask in the microtask queue is executed, one after another. the difference is that execution of microtasks continues until the queue is empty—even if new ones are scheduled in the interim. in other words, microtasks can enqueue new microtasks and those new microtasks will execute before the next task begins to run, and before the end of the current event loop iteration. problems because your code runs in the same thread, using the same event loop, as the browser's user interface, if your code blocks or enters an infinite loop, the browser itself will stall. even sluggish performance, whether caused by a bug or because of complex work being done by your code, can cause the use...
...a request. however, code running at a more fundamental level—such as code comprising a library or framework—may need a way to schedule code to be run at a safe time while still executing on the main thread, independent of the results of any single request or task. microtasks are another solution to this problem, providing a finer degree of access by making it possible to schedule code to run before the next iteration of the event loop begins, instead of having to wait until the next one. the microtask queue has been around for a while, but it's historiclaly been used only internally in order to drive things like promises. the addition of queuemicrotask(), exposing it to web developers, creates a unified queue for microtasks which is used wherever it's necessary to have the ability to sched...
Basic concepts - Web APIs
nsaction idbtransaction.oncomplete was fired only when all data was guaranteed to have been flushed to disk. 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. in this case the complete event is fired after the os has been told to write the data but potentially before that data has actually been flushed to disk. the event may thus be delivered quicker than before, however, there exists a small chance that the entire transaction will be lost if the os crashes or there is a loss of system power before the data is flushed to disk. since such catastrophic events are rare, most consumers should not need to concern themselves further. note: in firefox, if you wi...
...ransaction will be lost if the os crashes or there is a loss of system power before the data is flushed to disk. since such catastrophic events are rare, most consumers should not need to concern themselves further. note: in firefox, if you wish to ensure durability for some reason (e.g. you're storing critical data that cannot be recomputed later) you can force a transaction to flush to disk before delivering the complete event by creating a transaction using the experimental (non-standard) readwriteflush mode (see idbdatabase.transaction.) this is currently experimental, and can only be used if the dom.indexeddb.experimental pref is set to true in about:config. object store the mechanism by which data is stored in the database. the object store persistently holds records, which are...
...s, see using indexeddb. for the reference documentation on index, see idbkeyrange. key and value key a data value by which stored values are organized and retrieved in the object store. the object store can derive the key from one of three sources: a key generator, a key path, or an explicitly specified value. the key must be of a data type that has a number that is greater than the one before it. each record in an object store must have a key that is unique within the same store, so you cannot have multiple records with the same key in a given object store. a key can be one of the following types: string, date, float, a binary blob, and array. for arrays, the key can range from an empty value to infinity. and you can include an array within an array. alternatively, you can also lo...
Intersection Observer API - Web APIs
or 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 to grow or shrink each side of the root element's bounding box before computing intersections. defaults to all zeros. threshold either a single number or an array of numbers which indicate at what percentage of the target's visibility the observer's callback should be executed. if you only want to detect when visibility passes the 50% mark, you can use a value of 0.5. if you want the callback to run every time visibility passes another 25%, you would specify the ...
...all of the element's parts. similarly, if the visible portion of an element is not rectangular, the element's intersection rectangle is construed to be the smallest rectangle that contains all the visible portions of the element. it's useful to understand a bit about how the various properties provided by intersectionobserverentry describe an intersection. the intersection root and root margin before we can track the intersection of an element with a container, we need to know what that container is. that container is the intersection root, or root element. this can be either a specific element in the document which is an ancestor of the element to be observed, or null to use the document's viewport as the container. the root intersection rectangle is the rectangle used to check against the ...
...io. the result: not only does the color get changed, but the transparency of the target element changes, too; as the intersection ratio goes down, the background color's alpha value goes down with it, resulting in an element that's more transparent. similarly, if the intersectionratio is going down, we use the string decreasingcolor and replace the word "ratio" in that with the intersectionratio before setting the target element's background-color. finally, in order to track whether the intersection ratio is going up or down, we remember the current ratio in the variable prevratio. result below is the resulting content. scroll this page up and down and notice how the appearance of the box changes as you do so. there's an even more extensive example at timing element visibility with the in...
LocalFileSystem - Web APIs
, you need to create only one file system, but in a few cases, it might be useful to create a second one. for example, if you were to create a mail app, you might create a temporary storage for caching assets (like images and attachments) to speed up performance, while creating persistent storage for unique data—such as drafts of emails that were composed while offline—that should not be lost before they are backed up into the cloud. using persistent storage the requestfilesystem() method lets you ask for persistent or temporary storage. persistent storage is storage that stays in 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 b...
...once your user grants it, you don't need to call requestquota() again. subsequent calls are a noop. another api, the quota management api, lets you query an origin's current quota usage and allocation using window.webkitpersistentstorage.queryusageandquota(). to learn more, see this stackoverflow answer. (an older version of the api is described at managing h...
... domstring url, in entrycallback successcallback, in optional errorcallback errorcallback); constants constant value description temporary 0 transient storage that can be be removed by the browser at its discretion. persistent 1 storage that stays in the browser unless the user or the app expunges it. the user must grant permission before the app can use this type of storage. methods requestfilesystem() requests a file system where data should be stored. you access a sandboxed file system by requesting a localfilesystem object using this global method, window.requestfilesystem(). void requestfilesystem( in unsigned short type, in unsigned long long size, in filesystemcallback successcallback, in errorcallback err...
MutationObserver.observe() - Web APIs
notes reusing mutationobservers you can call observe() multiple times on the same mutationobserver to watch for changes to different parts of the dom tree and/or different types of changes. there are some caveats to note: if you call observe() on a node that's already being observed by the same mutationobserver, all existing observers are automatically removed from all targets being observed before the new observer is activated. if the same mutationobserver is not already in use on the target, then the existing observers are left alone and the new one is added. observation follows nodes when disconnected mutation observers are intended to let you be able to watch the desired set of nodes over time, even if the direct connections between those nodes are severed. if you begin watching a s...
...ation follows nodes when disconnected mutation observers are intended to let you be able to watch the desired set of nodes over time, even if the direct connections between those nodes are severed. ...
... theoretically, this means that if you keep track of the mutationrecord objects describing the changes that occur, you should be able to "undo" the changes, rewinding the dom back to its initial state. ...
ParentNode.prepend() - Web APIs
each node can be specified as either a node object or as a string; strings are inserted as new text nodes. return value undefined. exceptions hierarchyrequesterror: node cannot be inserted at the specified point in the hierarchy. ...
...each node can be specified as either a node object or as a string; strings are inserted as new text nodes. return value undefined. exceptions hierarchyrequesterror: node cannot be inserted at the specified point in the hierarchy. ...
... living standard initial definition. ...
Using the Payment Request API - Web APIs
l that the interaction has finished — you'd use this to carry out finishing steps, like updating the user interface to tell the user the transaction is complete, etc. other useful payment request methods there are some other useful payment request methods worth knowing about. paymentrequest.canmakepayment() can be used to check whether the paymentrequest object is capable of making a payment before you start the payment process. it returns a promise that fulfills with a boolean indicating whether it is or not, for example: // dummy payment request to check whether payment can be made new paymentrequest(buildsupportedpaymentmethoddata(), {total: {label: 'stub', amount: {currency: 'usd', value: '0.01'}}}) .canmakepayment() .then(function(result) { if(result) { ...
...text = "setup w3c checkout"; } }).catch(function(error) { // the user may have turned off the querying functionality in their // privacy settings. the website does not know whether they can make // a fast payment, so pick a generic title. checkoutbutton.innertext = "checkout with w3c"; }); } note: see our customizing the payment button demo for the full code. checking before all prices are known if the checkout flow needs to know whether paymentrequest.canmakepayment() will return true even before all line items and their prices are known, you can instantiate paymentrequest with dummy data and pre-query .canmakepayment(). if you call .canmakepayment() multiple times, keep in mind that the first parameter to the paymentrequest constructor should contain the same meth...
...erver and call `paymeresponse.complete()`. }).catch(function(error) { console.log(error); if (fallbacktolegacyonpaymentrequestfailure) { window.location.href = '/legacy-web-form-checkout'; } else { showcheckouterrortouser(); } }); } else { window.location.href = '/legacy-web-form-checkout'; } } note: see our checking user can make payments before prices are known demo for the full code. recommending a payment app when user has no apps if you select to pay with the bobpay demo payment provider on this merchant page, it tries to call paymentrequest.show(), while intercepting the notsupportederr exception. if this payment method is not supported, it redirects to the signup page for bobpay. the code looks something like this: checkoutbut...
PerformanceResourceTiming.fetchStart - Web APIs
example in the following example, the value of the *start and *end properties of all "resource" type events are logged. ...
... example in the following example, the value of the *start and *end properties of all "resource" type events are logged. ...
... example in the following example, the value of the *start and *end properties of all "resource" type events are logged. ...
PushEvent - Web APIs
Web › API › PushEvent
ed full support 16disabled disabled from version 16: this feature is behind the enable service workers preference. ...
...ed full support 16disabled disabled from version 16: this feature is behind the enable service workers preference. ...
...ed full support 16disabled disabled from version 16: this feature is behind the enable service workers preference. ...
Web Push API Notifications best practices - Web APIs
hen the browser is not running.” — an unnamed marketing site positive uses of push but there’s a bright and useful side to push notifications, too. let’s say you and your team commonly use a chat program to communicate, but today you’re happily working somewhere, and problem comes up. say your program manager found a hiccup in the approvals and wants to get your feedback on something before she proceeds. after a few failed attempts to get your attention, they send you an email, and your email app produces a push notification that successfully alerts you, even though your mail web app is not open. in this document, we’ll talk about the ethical use of web push notifications. sometimes they can eliminate frustration and annoyance, and sometimes they can cause them, and it’s up to...
...oyance, and sometimes they can cause them, and it’s up to you as a developer to make wise recommendations (and decisions) about the use of push notifications. what are you hoping to achieve with this push notification? as with everything, with great power comes great responsibility. every push notification should be useful and time-sensitive, and the user should always be asked for permission before sending the first one, and be offered an easy way to opt out of getting more in the future. there are some basic questions you can answer to determine if a push notification is needed: is there someone waiting in real-time for a response? in our above example, the program manager is awaiting your response and so a push notification is appropriate. is up-to-the minute updating necessary? i us...
...shows respect for the user, and a clear value to accepting push notifications. browser mitigations because of abuses of push notifications in the past, web browser developers have begun to implement strategies to help mitigate this problem. for example, safari 12.1 now requires—and other browsers either already do, or are planning[1] to do so—that the user interact with the page in some way before the page can request permission to perform push notifications. this at least prevents the user from getting spontaneously asked this question on web pages thaty've only glanced at once may rarely if ever look at again. [1] in the case of firefox, see bug 1524619, in which we find that firefox 68 implements this, disabled by default, behind the preference dom.webnotifications.requireuserinteracti...
ReadableStream.cancel() - Web APIs
mples in jake archibald's cancelling a fetch example, a stream is used to fetch the whatwg html spec chunk by chunk; each chunk is searched for the string "service workers". when the search terms is found, cancel() is used to cancel the stream — the job is finished so it is no longer needed. ...
... 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 ? ...
...see devtools for details. does the response lack cors...
Resource Timing API - Web APIs
vide a time value accurate to 5 µs (because, for example, due to hardware 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. ...
...lication can get timestamps for the various stages used to load a resource. the first property in the processing model is starttime which returns the timestamp immediately before the resource loading process begins. the fetchstart timestamps follows and redirect processing (if applicable) and preceeds dns lookup. the next stages are connectstart and connectend which are the timestamps immediately before and after connecting to the server, respectively. the last three timestamps are, in order: requeststart - the timestamp before the browser starts requesting the resource from the server; responsestart - the timestamp after the browser receives the first byte of the response from the server; and responseend - the timestamp after the browser receives the last byte of the resource. if the resource i...
...resource size the performanceresourcetiming interface has three properties that can be used to obtain size data about a resource. the transfersize property returns the size (in octets) of the fetched resource 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. other properties the nexthopprotocol property returns the network protocol used to fetch the resource. the initiatortype property returns the type of resource that initiated the performance entry such as "css...
Using the Screen Capture API - Web APIs
ing a screen capture stream: cursor indicates whether or not to capture the mouse cursor, and if so, whether to do so all the time or only while the mouse is in motion. the possible values are: always the mouse cursor should always be captured in the generated stream. motion the cursor should only be visible while moving, and, at the discretion of the user agent, for a brief time before after moving. then the cursor is removed from the stream. never the cursor should never be visible in the generated stream. logicalsurface a boolean which if true indicates that the capture should include offscreen areas of the source, if there are any. none of the constraints are applied in any way until after the content to capture has been selected. the contraints alter what you se...
...urces available for getdisplaymedia(). capturing shared audio getdisplaymedia() is most commonly used to capture video of a user's screen (or parts thereof). however, user agents may allow the capture of audio along with the video content. the source of this audio might be the selected window, the entire computer's audio system, or the user's microphone (or a combination of all of the above). before starting a project that will require sharing of audio, be sure to check the browser compatibility in mediadevices.getdisplaymedia() to see if the browsers you wish compaibility with have support for audio in captured screen streams. to request that the screen be shared with included audio, the options passed into getdisplaymedia() might look like this: const gdmoptions = { video: true, audi...
...sible in the shared stream. this effect can be amplified when capturing logical display surfaces, which may contain content that the user doesn't know about at all, let alone see. user agents which take privacy seriously should obfuscate content that is not actually visible onscreen, unless authorization has been given to share that content specifically. authorizing capture of display contents before streaming of captured screen contents can begin, the user agent will ask the user to confirm the sharing request, and to select the content to share. examples simple screen capture in this example, the contents of the captured screen area are simply streamed into a <video> element on the same page. javascript there isn't all that much code needed in order to make this work, and if you're f...
StereoPannerNode.StereoPannerNode() - Web APIs
s://github.com/mdn/browser-compat-data and send us a pull request. ...
... full support 53ie no support noopera full support 42safari no support nowebview android full support 55notes full support 55notes notes before chrome 59, the default values were not supported.chrome android full support 55notes full support 55notes notes before chrome 59, the default values were not supported.firefox android full support 53opera android full support ...
... ...
Streams API concepts - Web APIs
...
...eader. you can use whatever code you like to produce the chunks ready for writing; the writer plus the associated code is called a producer. when a writer is created and starts writing to a stream (an active writer), it is said to be locked to it. only one writer can write to a writable stream at one time. if you want another writer to start writing to your stream, you typically need to abort it before you then attach another writer to it. an internal queue keeps track of the chunks that have been written to the stream but not yet been processed by the underlying sink. there is also a construct you’ll use called a controller — each writer has an associated controller that allows you to control the stream (for example, to abort it if wished). you can make use of writable streams using t...
... ...
Text.splitText() - Web APIs
Web › API › Text › splitText
d node is returned to the caller. if the original node had a parent, the new node is inserted as the next sibling of the original node. if the offset is equal to the length of the original node, the newly created node has no data. separated text nodes can be concatenated using the node.normalize() method. syntax newnode = textnode.splittext(offset) parameters offset the index immediately before which to break the text node. return value returns a newly created text node that contains the text after the specified offset point. exceptions thrown a domexception with a value of index_size_err is thrown if the specified offset is negative or is greater than the number of 16-bit units in the node's text; a domexception with a value of no_modification_allowed_err is thrown if the node is ...
... living standard no change from document object model (dom) level 3 core specification. document object model (dom) level 3 core specificationthe definition ...
... living standard no change from document object model (dom) level 3 core specification. document object model (dom) level 3 core specificationthe definition of 'text.splittext' i...
WebGLRenderingContext.pixelStorei() - Web APIs
_default_webgl, gl.none webgl when using a webgl 2 context, the following values are available additionally: constant description type default value allowed values (for param) specified in gl.pack_row_length number of pixels in a row. glint 0 0 to infinity opengl es 3.0 gl.pack_skip_pixels number of pixel locations skipped before the first pixel is written into memory. glint 0 0 to infinity opengl es 3.0 gl.pack_skip_rows number of rows of pixel locations skipped before the first pixel is written into memory glint 0 0 to infinity opengl es 3.0 gl.unpack_row_length number of pixels in a row. glint 0 0 to infinity opengl es 3.0 gl.unpack_image_height im...
...ore the first pixel is written into memory glint 0 0 to infinity opengl es 3.0 gl.unpack_row_length number of pixels in a row. ...
... 0 to infinity opengl es 3.0 gl.unpack_image_height image height used for reading pixel data from memory glint 0 0 to infinity opengl es 3.0 gl.unpack_skip_pixels number of pixel images skipped before the first pixel is read from memory glint 0 0 to infinity opengl es 3.0 gl.unpack_skip_rows number of rows of pixel locations skipped before the first pixel is read from memory glint 0 0 to infinity opengl es 3.0 gl.unpack_skip_images number of pixel images skipped before the first pixel is read from memory glint 0 0 to infinity opengl es 3.0 examples setting the pixel storage mode affects the webglrenderingcontext.readpixels() operations, as well as unpacking of textures with the webglrende...
Adding 2D content to a WebGL context - Web APIs
imple square untextured plane, so let's start there, by building code to draw a square plane. the complete source code for this project is available on github. this project uses the glmatrix library to perform its matrix operations, so you will need to include that in your project. we're loading a copy from a cdn in our html's <head>. drawing the scene the most important thing to understand before we get started is that even though we're only rendering a square plane object in this example, we're still drawing in 3d space. it's just we're drawing a square and we're putting it directly in front of the camera perpendicular to the view direction. we need to define the shaders that will create the color for our simple scene as well as draw our object. these will establish how the square plane ...
...we'll do that using a function we call initbuffers(); as we explore more advanced webgl concepts, this routine will be augmented to create more -- and more complex -- 3d objects. function initbuffers(gl) { // create a buffer for the square's positions. const p...
...s very simple. it uses a few utility routines we'll cover shortly. function drawscene(gl, programinfo, buffers) { gl.clearcolor(0.0, 0.0, 0.0, 1.0); // clear to black, fully opaque gl.cleardepth(1.0); // clear everything gl.enable(gl.depth_test); // enable depth testing gl.depthfunc(gl.lequal); // near things obscure far things // clear the canvas before we start drawing on it. gl.clear(gl.color_buffer_bit | gl.depth_buffer_bit); // create a perspective matrix, a special matrix that is // used to simulate the distortion of perspective in a camera. // our field of view is 45 degrees, with a width/height // ratio that matches the display size of the canvas // and we only want to see objects between 0.1 units // and 100 units away fr...
Lifetime of a WebRTC session - Web APIs
s page is currently under construction, and some of the content will move to other pages as the webrtc guide material is built out. pardon our dust! establishing the connection the internet is big. really big. it’s so big that years ago, smart people saw how big it was, how fast it was growing, and the limitations of the 32-bit ip addressing system, and realized that something had to be done before we ran out of addresses to use, so they started working on designing a new 64-bit addressing system. but they realized that it would take longer to complete the transition than 32-bit addresses would last, so other smart people came up with a way to let multiple computers share the same 32-bit ip address. network address translation (nat) is a standard which supports this address sharing by handl...
...exchanged during signaling: control messages used to set up, open, and close the communication channel, and to handle errors. information needed in order to set up the connection: the ip addressing and port information needed for the peers to be able to talk to one another. media capability negotiation: what codecs and media data formats can the peers understand? these need to be agreed upon before the webrtc session can begin. only once signaling has been successfully completed can the true process of opening the webrtc peer connection begin. it's worth noting that the signaling server does not actually need to understand or do anything with the data being exchanged through it by the two peers during signaling. the signaling server is, in essence, a relay: a common point which both side...
... is up and running. then media shifts to the new network connection and the old one is closed. note: different browsers support ice restart under different sets of conditions. not all browsers will perform ice restart due to network congestion, for example. if you need to change the configuration of the connection in some way (such as changing to a different set of ice servers), you can do so before restarting ice by calling rtcpeerconnection.setconfiguration() with an updated rtcconfiguration dictionary before restarting ice. to explicitly trigger ice restart, simply start the renegotiation process by calling rtcpeerconnection.createoffer(), specifying the icerestart option with a value of true. then handle the connection process from then on just like you normally would. this generates ne...
Web Video Text Tracks Format (WebVTT) - Web APIs
t align:center size:35% what are you waiting for? webvtt cues a cue is a single subtitle block that has a single start time, end time, and textual payload. example 6 consists of the header, a blank line, and then five cues separated by blank lines. a cue consists of five components: an optional cue identifier followed by a newline. cue timings. optional cue settings with at least one space before the first and between each setting. one or more newlines. the cue payload text. example 7 - example of a cue 1 - title crawl 00:00:05.000 --> 00:00:10.000 line:0 position:20% size:60% align:start some time ago in a place rather distant.... cue identifier the identifier is a name that identifies the cue. it can be used to reference the cue from a script. it must not contain a newline and ca...
... the attribute kind is chapters then you cannot use tags. timestamp tag the timestamp must be greater that the cue's start timestamp, greater than any previous timestamp in the cue payload, and less than the cue's end timestamp. the active text is the text between the timestamp and the next timestamp or to the end of the payload if there is not another timestamp in the payload. any text before the active text in the payload is previous text . any text beyond the active text is future text . this enables karaoke style captions. example 12 - karaoke style text 1 00:16.500 --> 00:18.500 when the moon <00:17.500>hits your eye 1 00:00:18.500 --> 00:00:20.500 like a <00:19.000>big-a <00:19.500>pizza <00:20.000>pie 1 00:00:20.500 --> 00:00:21.500 that's <00:00:21.000>amore ...
...tregion the methods used for region are listed below along with description of their functionality: scrollsetting: for adjusting the scrolling setting of all nodes present in given region. vtt region constructor: for construction of new vtt regions. tutorial on how to write a webvtt file there are few steps that can be followed to write a simple webvtt file. before start, it must be noted that you can make use of a notepad and then save the file as ‘.vtt’ file. steps are given below: open a notepad. the first line of webvtt is standardized similar to the way some other languages require you to put headers as the file starts to indicate the file type. on the very first line you have to write: webvtt 3. leave the second line blank, and on the...
Fundamentals of WebXR - Web APIs
he web. together, these technologies are referred to as mixed reality, which is abbreviated xr. mixed reality is a large and complex subject, with much to learn and many other apis to bring together in order to create an engaging experience for users. in this guide, we provide a fundamental overview of what webxr is and how it works, as well as providing a foundation for what you'll need to know before you even begin to learn to develop augmented reality and virtual reality experiences for the web. what webxr is and isn't webxr is an api for web content and apps to use to interface with mixed reality hardware such as vr headsets and glasses with integrated augmented reality features. this includes both managing the process of rendering the views needed to simulate the 3d experience and the ab...
...ence is that webxr has integrated support for the advanced input controllers that are used with most mixed reality headsets, while webvr relied on the gamepad api to support the controllers. in webxr, the primary select and squeeze actions are directly supported using events, while other controls are available through a special webxr-specific implementation of the gamepad object. basic concepts before getting into too much detail, let's consider some basic concepts that you need to know before you learn how to develop xr code. field of view the term field of view (fov) is one which applies to any visual technology, from old film cameras to modern digital video cameras, including the cameras in computers and mobile devices. what is field of view? the field of view is, at its essence, the ex...
...d, 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 the background or skybox before rendering each frame. for more information about using webxr to create augmented reality 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 wh...
WebXR Device API - Web APIs
g to use the webgl context for webxr rendering. returns a promise which resolves once the context has been prepared, or is rejected if the context cannot be configured for use by webxr. guides and tutorials the following guides and tutorials are a great resource to learn how to comprehend webxr and the underlying 3d and vr/ar graphics concepts. foundations and basics fundamentals of webxr before diving into the details of how to create content using webxr, it may be helpful to read this overview of the technology, which includes introductions to terminology that may be unfamiliar to you, or which may be used in a new way. matrix math for the web a guide covering how matrices can be used on the web, including both for css transforms and for webgl purposes, as well as to handle the posit...
.... webxr application life cycle an overview of the overall life cycle of a webxr application, from startup to shutdown. this article serves as an introduction to the basics of what's involved in creating a webxr experience without diving into the code in detail. it's a good way to prepare for the next steps. creating a mixed reality experience starting up and shutting down a webxr session before actually presenting a scene using an xr device such as a headset or goggles, you need to create a webxr session bound to a rendering layer that draws the scene for presentation in each of the xr device's displays so that the 3d effect can be presented to the user. this guide covers how to create and stop webxr sessions. geometry and reference spaces in webxr in this guide, the required concepts...
... learn how to make use of these devices' controls. performance and security webxr performance guide recommendations and tips to help you optimize the performance of your webxr application. permissions and security for webxr the webxr device api has several areas of security to contend with, from establishing feature-policy to ensuring the user intends to use the mixed reality presentation before activating it. including other media positional audio in a 3d environment in 3d environments, which may either be 3d scenes rendered to the screen or a mixed reality experience experienced using a headset, it's important for audio to be performed so that it sounds like it's coming from the direction of its source. this guide covers how to accomplish this. playing video in a 3d environment ...
Web Audio API - Web APIs
ion general containers and definitions that shape audio graphs in web audio api usage. audiocontext the audiocontext interface represents an audio-processing graph built from audio modules linked together, each represented by an audionode. an audio context controls the creation of the nodes it contains and the execution of the audio processing, or decoding. you need to create an audiocontext before you do anything else, as everything happens inside a context. audiocontextoptions the audiocontextoptions dictionary is used to provide options when instantiating a new audiocontext. audionode the audionode interface represents an audio-processing module like an audio source (e.g. an html <audio> or <video> element), audio destination, intermediate processing module (e.g. a filter like biquad...
...node interface provides a compression effect, which lowers the volume of the loudest parts of the signal in order to help prevent clipping and distortion that can occur when multiple sounds are played and multiplexed together at once. gainnode the gainnode interface represents a change in volume. it is an audionode audio-processing module that causes a given gain to be applied to the input data before its propagation to the output. waveshapernode the waveshapernode interface represents a non-linear distorter. it is an audionode that use a curve to apply a waveshaping distortion to the signal. beside obvious distortion effects, it is often used to add a warm feeling to the signal. periodicwave describes a periodic waveform that can be used to shape the output of an oscillatornode. iirfilte...
...sponding audioworkletnode. audioworkletglobalscope the audioworkletglobalscope interface is a workletglobalscope-derived object representing a worker context in which an audio processing script is run; it is designed to enable the generation, processing, and analysis of audio data directly using javascript in a worklet thread rather than on the main thread. obsolete: script processor nodes before audio worklets were defined, the web audio api used the scriptprocessornode for javascript-based audio processing. because the code runs in the main thread, they have bad performance. the scriptprocessornode is kept for historic reasons but is marked as deprecated and will be removed in a future version of the specification. scriptprocessornode the scriptprocessornode interface allows the ...
Window: popstate event - Web APIs
window.onpopstate = () => settimeout(dosomething, 0); when popstate is sent when the transition occurs, either due to the user triggering the browser's "back" button or otherwise, the popstate event is near the end of the process to transition to the new location. it happens after the new location has loaded (if needed), displayed, made visible, and so on, after the pageshow event is sent, but before the persisted user state information is restored and the hashchange event is sent. to better understand when the popstate event is fired, consider this simplified sequence of events that occurs when the current history entry changes due to either the user navigating the site or the history being traversed programmatically. here, the transition is changing the current history entry to one we'll r...
...history entry changes due to either the user navigating the site or the history being traversed programmatically. here, the transition is changing the current history entry to one we'll refer to as new-entry. the current page's session history stack entry will be referred to as current-entry. if new-entry doesn't currently contain an existing document, fetch the content and create its document before continuing. this will eventually send events such as domcontentloaded and load to the window containing the document, but the steps below will continue to execute in the meantime. if current-entry's title wasn't set using one of the history api methods (pushstate() or replacestate(), set the entry's title to the string returned by its document.title attribute. if the browser has state informati...
... such as domcontentloaded and load to the window containing the document, but the steps below will continue to execute in the meantime. if current-entry's title wasn't set using one of the history api methods (pushstate() or replacestate(), set the entry's title to the string returned by its document.title attribute. if the browser has state information it wishes to store with the current-entry before navigating away from it, it then does so. the entry is now said to have "persisted user state." this information the browser might add to the history session entry may include, for instance, the document's scroll position, the values of form inputs, and other such data. if new-entry has a different document object than current-entry, the browsing context is updated so that its document property ...
WindowOrWorkerGlobalScope.setTimeout() - Web APIs
rameters function a function to be executed after the timer expires. code an alternative syntax that allows you to include a string instead of a function, which is compiled and executed when the timer expires. this syntax is not recommended for the same reasons that make using eval() a security risk. delay optional the time, in milliseconds (thousandths of a second), the timer should wait before the specified function or code is executed. if this parameter is omitted, a value of 0 is used, meaning execute "immediately", or more accurately, the next event cycle. note that in either case, the actual delay may be longer than intended; see reasons for delays longer than specified below. arg1, ..., argn optional additional arguments which are passed through to the function specified by func...
...leartimeout() 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 an alert box after two seconds</button> <p></p> <button onclick="clearalert();">cancel alert before it happens</button> javascript var timeoutid; function delayedalert() { timeoutid = window.settimeout(window.alert, 2*1000, 'that was really slow!'); } function clearalert() { window.cleartimeout(timeoutid); } result see also cleartimeout() example. polyfill if you need to pass one or more arguments to your callback function, but need it to work in browsers which don't support sen...
...terminated. for example: function foo() { console.log('foo has been called'); } settimeout(foo, 0); console.log('after settimeout'); will write to the console: after settimeout foo has been called this is because even though settimeout was called with a delay of zero, it's placed on a queue and scheduled to run at the next opportunity; not immediately. currently-executing code must complete before functions on the queue are executed, thus the resulting execution order may not be as expected. deferral of timeouts during pageload starting in firefox 66, firefox will defer firing settimeout and setinterval timers while the current tab is loading. firing is deferred until the mainthread is deemed idle (similar to window.requestidlecallback()), or until the load event is fired. maximum del...
XMLHttpRequest - Web APIs
e, xmlhttprequest can be used to retrieve any type of data, not just xml. if your communication needs to involve receiving event data or message data from a server, consider using server-sent events through the eventsource interface. for full-duplex communication, websockets may be a better choice. constructor xmlhttprequest() the constructor initializes an xmlhttprequest. it must be called before any other method calls. properties this interface also inherits properties of xmlhttprequesteventtarget and of eventtarget. xmlhttprequest.onreadystatechange an eventhandler that is called whenever the readystate attribute changes. xmlhttprequest.readystate read only returns an unsigned short, the state of the request. xmlhttprequest.response read only returns an arraybuffer, blob, d...
...uest.status, this includes the entire text of the response message ("200 ok", for example). note: according to the http/2 specification (8.1.2.4 response pseudo-header fields), http/2 does not define a way to carry the version or reason phrase that is included in an http/1.1 status line. xmlhttprequest.timeout is an unsigned long representing the number of milliseconds a request can take before automatically being terminated. xmlhttprequesteventtarget.ontimeout is an eventhandler that is called whenever the request times out. xmlhttprequest.upload read only is an xmlhttprequestupload, representing the upload process. xmlhttprequest.withcredentials is a boolean that indicates whether or not cross-site access-control requests should be made using credentials such as cookies or aut...
...equest.open() initializes a request. xmlhttprequest.overridemimetype() overrides the mime type returned by the server. xmlhttprequest.send() sends the request. if the request is asynchronous (which is the default), this method returns as soon as the request is sent. xmlhttprequest.setrequestheader() sets the value of an http request header. you must call setrequestheader()after open(), but before send(). non-standard methods xmlhttprequest.init() initializes the object for use from c++ code. warning: this method must not be called from javascript. xmlhttprequest.openrequest() initializes a request. this method is to be used from native code; to initialize a request from javascript code, use open() instead. see the documentation for open(). xmlhttprequest.sendasbinary() a var...
ARIA live regions - Accessibility
p and provide a way to programmatically expose dynamic content changes in a way that can be announced by assistive technologies. note: assistive technologies will announce dynamic changes in the content of a live region. including an aria-live attribute or a specialized live region role (such as role="alert") on the element you want to announce changes to works as long as you add the attribute before the changes occur — either in the original markup, or dynamically using javascript. simple live regions dynamic content which updates without a page reload is generally either a region or a widget. simple content changes which are not interactive should be marked as live regions. below is a list of each related aria live region property with a description. aria-live: the aria-live=politen...
...'click', event => { const planetsselect = document.queryselector('#planetsselect'); const selectedplanet = planetsselect.options[planetsselect.selectedindex].value; renderplanetinfo(selectedplanet); }); as the user selects a new planet, the information in the live region will be announced. because the live region has aria-live="polite", the screen reader will wait until the user pauses before announcing the update. thus, moving down in the list and selecting another planet will not announce updates in the live region. updates in the live region will only be announced for the planet finally chosen. here is a screenshot of voiceover on mac announcing the update (via subtitles) to the live region: preferring specialized live region roles in the following well-known predefined cases ...
...sers currently logged in. display a list of users where a user's log-in and log-out status will be reflected dynamically (without a page reload). <ul id="roster" aria-live="polite" aria-relevant="additions removals"> <!-- use javascript to add remove users here--> </ul> breakdown of aria live properties: aria-live="polite" indicates that the screen reader should wait until the user is idle before presenting updates to the user. this is the most commonly used value, as interrupting the user with "assertive" might interrupt their flow. aria-atomic is not set (false by default) so that only the added or removed users should be spoken and not the entire roster each time. aria-relevant="additions removals" ensures that both users added or removed to the roster will be spoken. ...
ARIA annotations - Accessibility
the semantics for this have long been available in html, via the <ins> and <del> elements: <p>freida’s pet is a <del>black cat called luna</del><ins>purple tyrannosaurus rex called tiny</ins>.</p> with the new additions, you now have new roles available to provide the same semantics, should you be unable to use <ins> and <del> el...
...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. <mark> is a suitable element for this purpose (a comment is a reference annotation), so the annotation could look like this: <p>the last half of the song is a slow-rising crescendo that peaks at the <mark aria-details="thread-1">end of the guitar solo</mark>, before fading away sharply.</p> <div role="comment" id="thread-1" data-author="chris"> <h3>chris said</h3> <p class="comment-text">i really think this moment could use more cowbell.</p> <p><time datetime="2019-03-30t19:29">march 30 2019, 19:29</time></p> </div> note: if for some reason you can’t use the <mark> element in your application, you could also use <span role="mark"></span>. since ...
.../div> note: if for some reason you can’t use the <mark> element in your application, you could also use <span role="mark"></span>. ...
Typical use cases of Flexbox - CSS: Cascading Style Sheets
ck for grid, and also in order to get alignment capabilities. this is something that may well change once box alignment is implemented in block layout. in this guide i look at some of the typical things you might use flexbox for today. navigation a common pattern for navigation is to have a list of items displayed as a horizontal bar. this pattern, as basic as it seems, was difficult to achieve before flexbox. it forms the most simple of flexbox examples, and could be considered the ideal flexbox 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. we either display the space outside of the items — therefore spacing them out with white space between or...
...th aligning items on the main axis. in the below live example we display the items at their natural size and by using justify-content: space-between make equal amounts of space between the items. you can change how the space is distributed using the space-around value, or where supported, space-evenly. 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. in this case we would use the flex properties to allow items to grow and shrink in proportion to one another as described in controlling ratios of flex items along th...
...happens. also in this example we are using margins on the flex items to create a gap between items, and a negative margin on the container in order that the items still remain flush with the right and left edges. until the gap properties from the box alignment specification are implemented in flexbox, we have to use margins in this way if we want to create a gutter between items. center item before flexbox, developers would joke that the hardest problem in web design was vertical centering. this has now been made straightforward using the alignment properties in flexbox, as the following live example shows. you can play with the alignment, aligning the item to the start with flex-start or end with flex-end. in the future we may not need to make a container a flex container just to centr...
Using CSS counters - CSS: Cascading Style Sheets
the given pseudo-element, from outermost to innermost, separated by the specified string. the counters are rendered in the specified style (decimal by default). basic example this example adds "section [the value of the counter]:" to the beginning of each heading. css body { counter-reset: section; /* set a counter named 'section', and its initial value is 0. ...
... counter-reset: section; /* set a counter named 'section', and its initial value is 0. */ } h3::before { counter-increment: section; /* increment the value of section counter by 1 */ content: "section " counter(section) ": "; /* display the word 'section ', the value of section counter, and a colon before the content of each h3 */ } html <h3>introduction</h3> <h3>body</h3> <h3>conclusion</h3> result nesting counters a css counter can be especially useful for making outlined lists, because a new instance of the counter is automatically created in child elements. using the counters() function, separating text can be inserted between differen...
...n child elements. using the counters() function, separating text can be inserted between different levels of nested counters. ...
Logical properties for margins, borders and padding - CSS: Cascading Style Sheets
ply 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 mode this css would apply a 5px margin to the top of the box and a 10px margin to the bottom. .box { margin-block: 5px 10px; } note: the shorthand properties margin-inline and margin-block shipped in firefox 66. as these are new properties check browser support before using. padding examples the mapped padding properties of padding-inline-start, padding-inline-end, padding-block-start, and padding-inline-end can be used instead of their physical counterparts. in the example below i have two boxes, one of which is using physical padding properties and the other logical padding properties. with a writing-mode of horizontal-tb, both boxes should appear the sa...
...ck — which allow you to set the padding of the two inline, and two block dimensions, respectively. in a horizontal writing-mode this css would apply 5px of padding to the top of the box and 10px of padding to the bottom: .box { padding-block: 5px 10px; } note: the shorthand properties padding-inline and padding-block shipped in firefox 66. as these are new properties check browser support before using. border examples the border properties are the main reason that logical properties and values seems to have so many properties, as we have the longhands for the color, width, and style of the border on each side of a box, along with the shorthand to set all three at once for each side. as with margin and padding we have a mapped version of each physical property. the demo below uses som...
...sion. the below code, in a horizontal writing mode, would give you a 2px green solid border on the top and bottom of the box, and a 4px dotted purple border on the left and right. .box { border-block: 2px solid green; border-inline-width: 4px; border-inline-style: dotted; border-inline-color: rebeccapurple; } note: these two value shorthands shipped in firefox 66, check browser support before using as other browsers may not have implemented them yet. flow relative border-radius properties the specification has fairly recently added flow-relative values for the border-radius longhands. these have not yet been implemented by any browser. the below example, in a horizontal writing-mode, would set the top-right border radius to 1em, the bottom-right to 0, the bottom-left to 20px and th...
Introducing the CSS Cascade - CSS: Cascading Style Sheets
Web › CSS › Cascade
e. some browsers let users modify the user-agent stylesheet. although some constraints on user-agent stylesheets are set by the html specification, browsers still have a lot of latitude: that means that significant differences exist from one browser to another. to simplify the development process, web developers often use a css reset style sheet, forcing common properties values to a known state before beginning to make alterations to suit their specific needs. author stylesheets author stylesheets are the most common type of style sheet. these are style sheets that define styles as part of the design of a given web page or site. the author of the page defines the styles for the document using one or more stylesheets, which define the look and feel of the website — its theme. user styleshe...
... */ author css 2: @media screen { li { margin-left: 3px } } @media print { li { margin-left: 1px } } user css: .specific { margin-left: 1em } html: <ul> <li class="specific">1<sup>st</sup></li> <li>2<sup>nd</sup></li> </ul> in this case, declarations inside li and .specific rules should apply. no declaration is marked as !important, so the precedence order is author style sheets before user style sheets or user-agent stylesheet. so three declarations are in competition: margin-left: 0 margin-left: 3px margin-left: 1px the last one is ignored (on a screen), and the first two have the same selector, hence the same specificity. therefore, it is the last one that is then selected: margin-left: 3px note that the declaration defined in the user css, though having a greater spe...
...rations are in competition: margin-left: 0 margin-left: 3px margin-left: 1px the last one is ignored (on a screen), and the first two have the same selector, hence the same specificity. therefore, it is the last one that is then selected: margin-left: 3px note that the declaration defined in the user css, though having a greater specificity, is not chosen as the cascade algorithm is applied before the specificity algorithm. specifications specification status comment css cascading and inheritance level 4 candidate recommendation added the revert keyword, which allows rolling a property back a cascade level. css cascading and inheritance level 3 candidate recommendation removed the override cascade origin, as it was never used in a w3c stan...
Specificity - CSS: Cascading Style Sheets
element is targeted by multiple declarations. as per css rules, directly targeted elements will always take precedence over rules which an element inherits from its ancestor. note: proximity of elements in the document tree has no effect on the specificity. selector types the following list of selector types increases by specificity: type selectors (e.g., h1) and pseudo-elements (e.g., ::before). class selectors (e.g., .example), attributes selectors (e.g., [type="radio"]) and pseudo-classes (e.g., :hover). id selectors (e.g., #example). universal selector (*), combinators (+, >, ~, ' ', ||) and negation pseudo-class (:not()) have no effect on specificity. (the selectors declared inside :not() do, however.) for more information, visit: "specificity" in "cascade and inheritance", yo...
...s directly with it. using !important, however, is bad practice and should be avoided because it makes debugging more difficult by breaking the natural cascading in your stylesheets. when two conflicting declarations with the !important rule are applied to the same element, the declaration with a greater specificity will be applied. some rules of thumb: always look for a way to use specificity before even considering !important only use !important on page-specific css that overrides foreign css (from external libraries, like bootstrap or normalize.css). never use !important when you're writing a plugin/mashup. never use !important on site-wide css. instead of using !important, consider: make better use of the css cascade use more specific rules. by indicating one or more elements ...
... even considering !important only use !important on page-specific css that overrides foreign css (from external libraries, like bootstrap or normalize.css). never use !important when you're writing a plugin/mashup. never use !important on site-wide css. instead of using !important, consider: make better use of the css cascade use more specific rules. by indicating one or more elements before the element you're selecting, the rule becomes more specific and gets higher priority: <div id="test"> <span>text</span> </div> div#test span { 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 no...
animation-delay - CSS: Cascading Style Sheets
the animation can start later, immediately from its beginning, or immediately and partway through the animation. the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. it is often convenient to use the shorthand property animation to set all animation properties at once. ...
...moment the animation is applied to the element. 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 definition initial value0sapplies toall elements, ::before and ::after pseudo-elementsinheritednocomputed valueas specifiedanimation typediscrete formal syntax <time># examples see css animations for examples. specifications specification status comment css animationsthe definition of 'animation-delay' in that specification. working draft initial definition. browser compatibility the compatibility table on ...
...this bug affects only some platforms, such as windows. full support 49prefixed prefixed implemented with the vendor prefix: -webkit- full support 44prefixed disabled prefixed implemented with ...
counters() - CSS: Cascading Style Sheets
Web › CSS › counters
er-roman) a counter has no visible effect by itself. the counters() function (and counter() function) is what makes it useful by returning developer defined content. note: the counters() function can be used with any css property, but support for properties other than content is experimental, and support for the type-or-unit parameter is sparse. check the browser compatibility table carefully before using this in production. syntax values <custom-ident> a name identifying the counters, which is the same case-sensitive name used for the counter-reset and counter-increment. the name cannot start with two dashes and can't be none, unset, initial, or inherit. <counter-style> a counter style name or symbols() function, where a counter style name is a numeric, alphabetic, or symbolic sim...
... </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 { 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> ...
... working draft no change css level 2 (revision 1)the definition of 'css counters' in that specification. recommendatio...
Challenge solutions - Developer guides
strong { color: #f00; /* red */ background-color: #ddf; /* pale blue */ font: 200% serif; } .carrot { color: #fa0; /* orange */ } .spinach { color: #080; /* dark green */ } p { color: #00f; /* blue */ } content add an image challenge add a one rule to your stylesheet so that it displays the image at the start of each line. solution add this rule to your stylesheet: p:before{ content: url("yellow-pin.png"); } lists lower roman numerals challenge add a rule to your stylesheet, to number the oceans using roman numerals from i to v. solution define a rule for list items to use the lower-roman list style: li { list-style: lower-roman; } capital letters challenge change your stylesheet to identify the headings with capital letters in parentheses.
... use the lower-roman list style: li { list-style: lower-roman; } capital letters challenge change your stylesheet to identify the headings with capital letters in parentheses. solution add a rule to the body element (parent of the headings) to reset a new counter, and one to display and increment the counter on the headings: /* numbered headings */ body {counter-reset: headnum;} h3:before { content: "(" counter(headnum, upper-latin) ") "; counter-increment: headnum; } boxes ocean border challenge add one rule to your stylesheet, making a wide border all around the oceans in a color that reminds you of the sea. solution the following rule achieves this effect: ul { border: 10px solid lightblue; width: 100px; } layout default image position fixed image...
...border challenge add one rule to your stylesheet, making a wide border all around the oceans in a color that reminds you of the sea. solution the following rule achieves this effect: ul { border: 10px solid lightblue; width: 100px; } layout default image position fixed image position challenge change your sample document, doc2.html, adding this tag to it near the end, just before </body>: <img id="fixed-pin" src="yellow-pin.png" alt="yellow map pin"> predict where the image will appear in your document. then refresh your browser to see if you were correct. solution the image appears to the right of the second list. challenge add a rule to your stylesheet that places the image in the top right of your document. solution the following rule achieves the desired resu...
HTML attribute: rel - HTML: Hypertext Markup Language
Web › HTML › Attributes › rel
ause it uses an unsupported format, the browser proceeds to the next-most appropriate, and so on. note: apple's ios does not use this link type, nor the sizes attribute, like others mobile browsers do, to select a webpage icon for web clip or a start-up placeholder. instead it uses the non-standard apple-touch-icon and apple-touch-startup-image respectively. the shortcut link type is often seen before icon, but this link type is non-conforming, ignored and web authors must not use it anymore. alternate indicates an alternate representation of the current document. valid for link, a, and area, the meaning depends on the values of the other attributes. with the stylesheet keyword on a <link>, it creates an alternate stylesheet. <!-- a persistent style sheet --> <link rel="stylesheet" ...
...se it uses an unsupported format, the browser proceeds to the next-most appropriate, and so on. note: apple's ios does not use this link type, nor the sizes attribute, like others mobile browsers do, to select a webpage icon for web clip or a start-up placeholder. instead it uses the non-standard apple-touch-icon and apple-touch-startup-image respectively. the shortcut link type is often seen before icon, but this link type is non-conforming, ignored and web authors must not use it anymore. license valid on the <a>, <area>, <form>, <link> elements, the license value indicates that the hyperlink leads to a document describing the licensing information; that the main content of the current document is covered by the copyright license described by the referenced document. if not inside th...
...ss-origin fetching. modulepreload useful for improved performance, and relevant to the <link> anywhere in the document, setting rel="modulepreload" tells the browser to preemptively fetch the script (and dependencies) and store it in the document's module map for later evaluation. modulepreload links can ensure network fetching is done with the module ready (but not evaluated) in the module map before it is necessarily needed. see also link types: modulepreload. next relevant to <form>, <link>, <a>, and <area>, the next values indicates that the current document is a part of a series, and that the next document in the series is the referenced document. when included in a <link>, browsers may assume that document will be fetched next, and treat it as a resource hint. nofollow relevant to <f...
<input type="datetime-local"> - HTML: Hypertext Markup Language
cal, and the variations in how the inputs work, it may currently still be best to use a framework or library to present these, or to use a custom input of your own. another option is to use separate date and time inputs, each of which is more widely supported than datetime-local. some browsers may resort to a text-only input element that validates that the results are legitimate date/time values before letting them be delivered to the server, as well, but you shouldn't rely on this behavior since you can't easily predict it. for those of you not using a supporting browser, the chrome/opera datetime-local control looks like the below screenshot. clicking the down arrow on the right hand side brings up a date picker to allow you to choose a date; you have to enter the time manually. the edge ...
...it virtual machine, but most vms don't support this kind of virtualization, stability may suffer, and performance will definately suffer greatly. the y10k problem (often client-side) in many servers, dates are stored as numbers instead of as strings--numbers of a fixed size and agnostic of format (aside from endianness). after the year 10,000, those numbers will just be a little bit bigger than before, so many servers will not see issues with forms submitted after the year 10,000. the problem is with the client side of things: parsing of dates with more than 4 digits in the year. <!--midnight of january 1st, 10000: the exact time of y10k--> <input type="datetime-local" value=""+010000-01-01t05:00"/> it's that simple. just prepare your code for any number of digits. do not only prepare for 5...
...f(dayselect.value === "") { dayselect.value = previousday - 1; } if(dayselect.value === "") { dayselect.value = previousday - 2; } if(dayselect.value === "") { dayselect.value = previousday - 3; } } } function populateyears() { // get this year as a number var date = new date(); var year = date.getfullyear(); // make this year, and the 100 years before it available in the year <select> for(var i = 0; i <= 100; i++) { var option = document.createelement('option'); option.textcontent = year-i; yearselect.appendchild(option); } } function populatehours() { // populate the hours <select> with the 24 hours of the day for(var i = 0; i <= 23; i++) { var option = document.createelement('option'); option.textcontent = (i < 1...
<input type="image"> - HTML: Hypertext Markup Language
Web › HTML › Element › input › image
ription alt alternate string to display when the image can't be shown formaction the url to which to submit the data formenctype the encoding method to use when submitting the form data formmethod the http method to use when submitting the form formnovalidate a boolean which, if present, indicates that the form shouldn't be validated before submission formtarget a string indicating a browsing context from where to load the results of submitting the form height the height, in css pixels, at which to draw the image src the url from which to load the image width the width, in css pixels, at which to draw the image alt the alt attribute provides an alternate string to use as the bu...
...method supports complex data and file attachments. dialog this method is used to indicate that the button simply closes the dialog with which the input is associated, and does not transmit the form data at all. this attribute is also available on <input type="submit"> and <button> elements. formnovalidate a boolean attribute which, if present, specifies that the form should not be validated before submission to the server. this overrides the value of the novalidate attribute on the element's owning form. this attribute is also available on <input type="submit"> and <button> elements. formtarget a string which specifies a name or keyword that indicates where to display the response received after submitting the form. the string must be the name of a browsing context (that is, a tab, wind...
..., and the object-fit property to control how the image's size is adjusted to fit within the frame. this allows you to specify a frame for the image using the width and height attributes to set aside space in the layout, then adjust where within that space the image is located and how (or if) it is scaled to occupy that space. examples a login form the following example shows the same button as before, but included in the context of a typical login form. html <form> <p>login to your account</p> <div> <label for="userid">user id</label> <input type="text" id="userid" name="userid"> </div> <div> <label for="pwd">password</label> <input type="password" id="pwd" name="pwd"> </div> <div> <input id="image" type="image" src="/static/external/62/62ac2ecddbec0e0b5400...
<input type="tel"> - HTML: Hypertext Markup Language
Web › HTML › Element › input › tel
the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. ...
...may vary from one browser to another, typically clicking in the edit box presents a drop-down of the suggested email addresses. then, as the user types, the list is adjusted to show only filtered matching values. each typed character narrows down the list until the user makes a selection or types a custom value. here's a screenshot of what that might look like: validation as we've touched on before, it's quite difficult to provide a one-size-fits-all client-side validation solution for phone numbers. so what can we do? let's consider some options. important: html form validation is not a substitute for server-side scripts that ensure the entered data is in the proper format before it is allowed into the database. it's far too easy for someone to make adjustments to the html that allow th...
...after { position: absolute; content: '✓'; padding-left: 5px; color: #009000; } the output looks like this: pattern validation if you want to further restrict entered numbers so they also have to conform to a specific pattern, you can use the pattern attribute, which takes as its value a regular expression that entered values have to match. ...
<textarea> - HTML: Hypertext Markup Language
Web › HTML › Element › textarea
input) element for a full explanation. readonly this boolean attribute indicates that the user cannot modify the value of the control. unlike the disabled attribute, the readonly attribute does not prevent the user from clicking or selecting in the control. the value of a read-only control is still submitted with the form. required this attribute specifies that the user must fill in a value before submitting a form. rows the number of visible text lines for the control. spellcheck specifies whether the <textarea> is subject to spell checking by the underlying browser/os. the value can be: true: indicates that the element needs to have its spelling and grammar checked. default : indicates that the element is to act according to a default behavior, possibly based on the parent elem...
...other major browsers place the insertion point at the beginning of the text.notes a default background-image gradient is applied to all <textarea> elements, which can be disabled using background-image: none.ie full support yesopera ...
...other major browsers place the insertion point at the beginning of the text.notes a default background-image gradient is applied to all <textarea> elements, which can be disabled using background-image: none.opera android full support yessafari i...
Link types - HTML: Hypertext Markup Language
ical_link_element a canonical link element is an html element that helps webmasters prevent duplicate content issues by specifying the "canonical" or "preferred" version of a web page as part of search engine optimization. <link> <a>, <area>, <form> dns-prefetch hints to the browser that a resource is needed, allowing the browser to do a dns lookup and protocol handshaking before a user clicks the link. <link> <a>, <area>, <form> external indicates that the hyperlink leads to a resource outside the site of the current page; that is, following the link will make the user leave the site. <a>, <area>, <form> <link> first indicates that the hyperlink leads to the first resource of the sequence the current page is in. note: other ...
...unsupported format, the browser proceeds to the next-most appropriate, and so on. note: apple's ios does not use this link type, nor the sizes attribute, like others mobile browsers do, to select a webpage icon for web clip or a start-up placeholder. instead it uses the non-standard apple-touch-icon and apple-touch-startup-image respectively. the shortcut link type is often seen before icon, but this link type is non-conforming, ignored and web authors must not use it anymore. <link> <a>, <area>, <form> import html imports <link> <a>, <area>, <form> index obsolete since html5 indicates that the page is part of a hierarchical structure and that the hyperlink leads to the top level resource of that structure. if one or several up lin...
...ote that when noopener is used, nonempty target names other than _top, _self, and _parent are all treated like _blank in terms of deciding whether to open a new window/tab. <a>, <area>, <form> <link> noreferrer prevents the browser, when navigating to another page, to send this page address, or any other value, as referrer via the referer: http header. (in firefox, before firefox 37, this worked only in links found in pages. links clicked in the ui, like "open in a new tab" via the contextual menu, ignored this). <a>, <area>, <form> <link> opener reverts implicit rel="noopener" addition on links with target="_blank" (see related html spec discussion, webkit change, and firefox bug discussion). <a>, <area>, <form> <link> ...
Using the application cache - HTML: Hypertext Markup Language
lback section of the cache manifest. the section header line may include whitespaces, but must include the colon (:) in the section name. section data the format for lines of data varies from section to section. in the explicit (cache:) section, each line is a valid uri or iri reference to a resource to cache (no wildcard characters are allowed in this sections). whitespace is allowed before and after the uri or iri on each line. in the fallback section each line is a valid uri or iri reference to a resource, followed by a fallback resource that is to be served up when a connection with the server cannot be made. in the network section, each line is a valid uri or iri reference to a resource to fetch from the network (or the wildcard character * can be used in this section). note: r...
...event, which is fired instead of the cached event when a new update has been downloaded but not yet activated using the swapcache() method. obsolete the application cache group is now obsolete. testing for updates to the cache manifest you can programmatically test to see if an application has an updated cache manifest file, using javascript. since a cache manifest file may have been updated before a script attaches event listeners to test for updates, scripts should always test window.applicationcache.status. function onupdateready() { console.log('found new version!'); } window.applicationcache.addeventlistener('updateready', onupdateready); if(window.applicationcache.status === window.applicationcache.updateready) { onupdateready(); } to manually start testing for a new manifest fi...
...o get it from network. to link to cached resources that have parameters parsed in javascript use parameters in the hash part of the link, such as other-cached-page.html#whatever?parametername=value. when applications are cached, simply updating the resources (files) that are used in a web page is not enough to update the files that have been cached. you must update the cache manifest file itself before the browser retrieves and uses the updated files. you can do this programmatically using window.applicationcache.swapcache(), though resources that have already been loaded will not be affected. to make sure that resources are loaded from a new version of the application cache, refreshing the page is ideal. it's a good idea to set expires headers on your web server for *.appcache files to expire...
Browser detection using the user agent - HTTP
detecting the browser is needed. using the user agent to detect the browser looks simple, but doing it well is, in fact, a very hard problem. this document will guide you in doing this as correctly as possible. it's worth re-iterating: it's very rarely a good idea to use user agent sniffing. you can almost always find a better, more broadly compatible way to solve your problem! considerations before using browser detection when considering using the user agent string to detect which browser is being used, your first step is to try to avoid it if possible. start by trying to identify why you want to do it. are you trying to work around a specific bug in some version of a browser? look, or ask, in specialized forums: you're unlikely to be the first to hit this problem. also, experts, or s...
... console.log(splitupstring("jqwhy")); // ["jq", "w", "hy"] the above code would have made several incorrect assumptions: it assumed that all user agent strings that include the substring "chrome" are chrome. ua strings are notoriously misleading. it assumed that the lookbehind feature would always be available if the browser was chrome. the agent might be an older version of chrome, from before support was added, or (because the feature was experimental at the time) it could be a later version of chrome that removed it. most importantly, it assumed no other browsers would support the feature. support could have been added to other browsers at any time, but this code would have continued choosing the inferior path. problems like these can be avoided by testing for support of the fe...
... your webpage until you can open up the dev tools side panel and resize the screen while the webpage looks smooth, fluid, and dynamically resized. the simplest way to do this is to separate all the code that moves content around based on screen size to a single function that is called when the page is loaded and at each resize event thereafter. if there is a lot calculated by this layout function before it determines the new layout of the page, then consider debouncing the event listener such that it is not called as often. also note that there is a huge difference between the media queries (max-width: 25em), not all and (min-width: 25em), and (max-width: 24.99em): (max-width: 25em) excludes (max-width: 25em), whereas not all and (min-width: 25em) includes (max-width: 25em). (max-width: 24.99em)...
HTTP caching - HTTP
Web › HTTP › Caching
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 and a full response is downloaded each and every time. cache-control: no-store cache but revalidate a cache will send the request to the origin server for validation before releasing a cached copy. cache-control: no-cache private and public caches the "public" directive indicates that the response may be cached by any cache. this can be useful if pages with http authentication, or response status codes that aren't normally cacheable, should now be cached. on the other hand, "private" indicates that the response is intended for a single user only and must not be ...
... the request. for the files in the application that will not change, you can usually add aggressive caching. this includes static files such as images, css files and javascript files, for example. for more details, see also the freshness section below. cache-control: max-age=31536000 validation when using the "must-revalidate" directive, the cache must verify the status of the stale resources before using it and expired ones should not be used. for more details, see the validation section below. cache-control: must-revalidate the pragma header pragma is a http/1.0 header, it is not specified for http responses and is therefore not a reliable replacement for the general http/1.1 cache-control header, although it does behave the same as cache-control: no-cache, if the cache-control header f...
... served by the cache forever. caches have finite storage so items are periodically removed from storage. this process is called cache eviction. on the other side, some resources may change on the server so the cache should be updated. as http is a client-server protocol, servers can't contact caches and clients when a resource changes; they have to communicate an expiration time for the resource. before this expiration time, the resource is fresh; after the expiration time, the resource is stale. eviction algorithms often privilege fresh resources over stale resources. note that a stale resource is not evicted or ignored; when the cache receives a request for a stale resource, it forwards this request with a if-none-match to check if it is in fact still fresh. if so, the server returns a 304 (no...
HTTP Index - HTTP
Web › HTTP › Index
, http header, privacy, reference, referrer-policy, response, response header, referrer the referrer-policy http header controls how much referrer information (sent via the referer header) should be included with requests. 176 retry-after http, reference, response, response header, header the retry-after response http header indicates how long the user agent should wait before making a follow-up request. there are three main cases this header is used: 177 save-data http, http header, reference, request header, save-data, header the save-data header field is a boolean which, in requests, indicates the client's preference for reduced data usage. this could be for reasons such as high transfer costs, slow connection speeds, etc. 178 sec-web...
... 209 get http, reference, request method the http get method requests a representation of the specified resource. requests using get should only retrieve data. 210 head http, reference, request method the http head method requests the headers that are returned if the specified resource would be requested with an http get method. such a request can be done before deciding to download a large resource to save bandwidth, for example. 211 options http, reference, request method the http options method is used to describe the communication options for the target resource. the client can specify a url for the options method, or an asterisk (*) to refer to the entire server. 212 patch http, http method, reference, request met...
...tus code, success the http 200 ok success status response code indicates that the request has succeeded. a 200 response is cacheable by default. 222 201 created http, reference, status code, success the http 201 created success status response code indicates that the request has succeeded and has led to the creation of a resource. the new resource is effectively created before this response is sent back and the new resource is returned in the body of the message, its location being either the url of the request, or the content of the location header. 223 202 accepted http, reference, status code, success response the hypertext transfer protocol (http) 202 accepted response status code indicates that the request has been received but not yet acted u...
An overview of HTTP - HTTP
Web › HTTP › Overview
operate at the transport, network or physical levels, becoming transparent at the http layer and potentially making a significant impact on performance. those operating at the application layers are generally called proxies. these can be transparent, forwarding on the requests they receive without altering them in any way, or non-transparent, in which case they will change the request in some way before passing it along to the server. proxies may perform numerous functions: caching (the cache can be public or private, like the browser cache) filtering (like an antivirus scan or parental controls) load balancing (to allow multiple servers to serve the different requests) authentication (to control access to different resources) logging (allowing the storage of historical information) bas...
...ayer, and therefore fundamentally out of scope for http. though http doesn't require the underlying transport protocol to be connection-based; only requiring it to be reliable, or not lose messages (so at minimum presenting an error). among the two most common transport protocols on the internet, tcp is reliable and udp isn't. http therefore relies on the tcp standard, which is connection-based. before a client and server can exchange an http request/response pair, they must establish a tcp connection, a process which requires several round-trips. the default behavior of http/1.0 is to open a separate tcp connection for each http request/response pair. this is less efficient than sharing a single tcp connection when multiple requests are sent in close succession. in order to mitigate this flaw...
...flow when a client wants to communicate with a server, either the final server or an intermediate proxy, it performs the following steps: open a tcp connection: the tcp connection is used to send a request, or several, and receive an answer. the client may open a new connection, reuse an existing connection, or open several tcp connections to the servers. send an http message: http messages (before http/2) are human-readable. with http/2, these simple messages are encapsulated in frames, making them impossible to read directly, but the principle remains the same. for example: get / http/1.1 host: developer.mozilla.org accept-language: fr read the response sent by the server, such as: http/1.1 200 ok date: sat, 09 oct 2010 14:28:02 gmt server: apache last-modified: tue, 01 dec 2009 20...
JavaScript modules - JavaScript
modules and classes as we hinted at earlier, you can also export and import classes; this is another option for avoiding conflicts in your code, and is especially useful if you've already got your module code written in an object-oriented style. you can see an example of our shape drawing module rewritten ...
...classes example. this time however we are not drawing anything on the canvas when the example loads. instead, we include three buttons — "circle", "square", and "triangle" — that, when pressed, dynamically load the required module and then use it to draw the associated shape. in this example we've only made changes to our index.html and main.js files — the module exports remain the same as before. over in main.js we've grabbed a reference to each button using a document.queryselector() call, for example: let squarebtn = document.queryselector('.square'); we then attach an event listener to each button so that when pressed, the relevant module is dynamically loaded and used to draw the shape: squarebtn.addeventlistener('click', () => { import('./modules/square.js').then((module) => {...
... that, because the promise fulfillment returns a module object, the class is then made a subfeature of the object, hence we now need to access the constructor with module. prepended to it, e.g. module.square( ... ). troubleshooting here are a few tips that may help you if you are having trouble getting your modules to work. feel free to add to the list if you discover more! we mentioned this before, but to reiterate: .js files need to be loaded with a mime-type of text/javascript (or another javascript-compatible mime-type, but text/javascript is recommended), otherwise you'll get a strict mime type checking error like "the server responded with a non-javascript mime type". if you try to load the html file locally (i.e. with a file:// url), you'll run into cors errors due to javascript mod...
Array.prototype.forEach() - JavaScript
ked with three arguments: the value of the element the index of the element the array object being traversed if a thisarg parameter is provided to foreach(), it will be used as callback's this value. the thisarg value ultimately observable by callback is determined according to the usual rules for determining the this seen by a function. the range of elements processed by foreach() is set before the first invocation of callback. elements which are appended to the array after the call to foreach() begins will not be visited by callback. if existing elements of the array are changed or deleted, their value as passed to callback will be the value at the time foreach() visits them; elements that are deleted before being visited are not visited. if elements that are already visited are remove...
...[1,3,,7] let numcallbackruns = 0 arraysparse.foreach((element) => { console.log(element) numcallbackruns++ }) console.log("numcallbackruns: ", numcallbackruns) // 1 // 3 // 7 // numcallbackruns: 3 // comment: as you can see the missing value between 3 and 7 didn't invoke callback function. converting a for loop to foreach const items = ['item1', 'item2', 'item3'] const copyitems = [] // before for (let i = 0; i < items.length; i++) { copyitems.push(items[i]) } // after items.foreach(function(item){ copyitems.push(item) }) printing the contents of an array note: in order to display the content of an array in the console, you can use console.table(), which prints a formatted version of the array. the following example illustrates an alternative approach, using foreach(). the ...
...looks like obj1 now modifying the array during iteration the following example logs one, two, four. when the entry containing the value two is reached, the first entry of the whole array is shifted off—resulting in all remaining entries moving up one position. because element four is now at an earlier position in the array, three will be skipped. foreach() does not make a copy of the array before iterating. let words = ['one', 'two', 'three', 'four'] words.foreach((word) => { console.log(word) if (word === 'two') { words.shift() //'one' will delete from array } }) // one // two ​​​​// four console.log(words); //['two', 'three',​​​​ 'four'] flatten an array the following example is only here for learning purpose. if you want to flatten an array using built-...
Lexical grammar - JavaScript
ed this way. hashbang comments a specialized third comment syntax, the hashbang comment, is in the process of being standardized in ecmascript (see the hashbang grammar proposal). a hashbang comment behaves exactly like a single line-only (//) comment. instead, it begins with #! and is only valid at the absolute start of a script or module. note also that no whitespace of any kind is permitted before the #!. the comment consists of all the characters after #! up to the end of the first line; only one such comment is permitted. the hashbang comment specifies the path to a specific javascript interpreter that you want to use to execute the script. an example is as follows: #!/usr/bin/env node console.log("hello world"); note: hashbang comments in javascript mimic shebangs in unix used to ...
... after #! up to the end of the first line; only one such comment is permitted. the hashbang comment specifies the path to a specific javascript interpreter that you want to use to execute the script. an example is as follows: #!/usr/bin/env node console.log("hello world"); note: hashbang comments in javascript mimic shebangs in unix used to run files with proper interpreter. although bom before hashbang comment will work in a browser it is not advised to use bom in a script with hasbang. bom will not work when you try to run the script in unix/linux. so use utf-8 without bom if you want to run scripts directly from shell. you must only use the #! comment style to specify a javascript interpreter. in all other cases just use a // comment (or mulitiline comment). keywords reserved key...
...olon insertion some javascript statements must be terminated with semicolons and are therefore affected by automatic semicolon insertion (asi): empty statement let, const, variable statement import, export, module declaration expression statement debugger continue, break, throw return the ecmascript specification mentions three rules of semicolon insertion. 1. a semicolon is inserted before, when a line terminator or "}" is encountered that is not allowed by the grammar. { 1 2 } 3 // is transformed by asi into { 1 2 ;} 3; 2. a semicolon is inserted at the end, when the end of the input stream of tokens is detected and the parser is unable to parse the single input stream as a complete program. here ++ is not treated as a postfix operator applying to variable b, because a line t...
while - JavaScript
if this condition evaluates to true, statement is executed. ...
...if this condition evaluates to true, statement is executed. when condition 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. ...
...s condition evaluates to true, statement is executed. when condition 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. examples using while the following while loop iterates as long as n is less than three. var n = 0; var x = 0; while (n < 3) { n++; x += n; } each iteration, the loop increments n and adds it to x. therefore, x and n take on the following values: after the first pass: n = 1 and x = 1 after the second pass: n = 2 and x = 3 after the third pass: n = 3 and...
Digital audio concepts - Web media technologies
d 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 useful for audio mastering, where you need as much quality as possible while manipulating and editing the sound before downsampling to the sample rate you will use for the final product. this is similar to how photographers will use high resolution images for editing and compositing before presenting the customer with a jpeg suitable for use on a web site. audio file size and network bandwidth once you know the size of a single audio frame and how many frames per second make up your audio data, you can easily c...
...erstanding of psychoacoustics, it's possible to design a compression method that will minimize the compressed size of the audio while maximizing the percieved fidelity of the sound. an algorithm employing psychoacoustics may use any of the techniques mentioned here, and will almost certainly apply others as well. ...
...ate by taking advantage of the way humans determine the location of sounds in space; this is called sound localization. we hear in stereo because our ears detect a sound at different times depending on where the sound is coming from. this is because our ears are separated by several inches, thanks to being on opposite sides of our heads. a sound coming from our right will arrive at our right ear before it arrives at our left ear. our brains determine where the sound is in the space around us by using that time difference to figure out the angle from which the sound is coming. however, as the frequency of the audio signal goes up, the wavelength goes up as well. eventually, the wavelength approaches then exceeds the distance between the ears, and it becomes difficult or impossible to unambiguous...
Media container formats (file types) - Web media technologies
o provide media in a single format, choose a format that's available on the broadest selection of devices and browsers, such as mp3 (for audio) or mp4 (for video and/or audio). if your media is audio-only, choosing an audio-only container format likely makes sense. now that the patents have all expired, mp3 is a widely supported and good choice. wave is good but uncompressed, so be aware of that before using it for large audio samples. flac is a very good choice, due to its lossless compression, if the target browsers all support it. unfortunately, neither of the relatively major lossless compression formats (flac and alac) are universally supported. flac is the more broadly supported of the two, but is not supported by macos without additional software installed, and is not supported at all ...
...s without additional software installed, and is not supported at all on ios. if you need to offer lossless audio, you may need to provide both flac and alac to get close to universal compatibility. container selection advice the tables below offer suggested containers to use in various scenarios. these are just suggestions. be sure to consider the needs of your application and your organization before selecting a container format. audio-only files if you need... consider using this container format compressed files for general-purpose playback mp3 (mpeg-1 audio layer iii) losslessly compressed files flac with alac fallback uncompressed files wav now that mp3's patents have all expired, the choice of audio file format has become much ...
...bm (ideally with mp4 fallback) general purpose video mp4 (ideally with webm or ogg fallback) high compression optimized for slow connections 3gp (ideally with mp4 fallback) compatibility with older devices/browsers quicktime (ideally with avi and/or mpeg-2 fallback) these suggestions make a number of assumptions. you should carefully consider the options before making a final decision, especially if you have a lot of media that will need to be encoded. maximizing compatibility with multiple containers to optimize compatibility, it's worth considering providing more than one version of media files, using the <source> element to specify each source within the <audio> or <video> element. for example, you can offer an ogg or webm video as the first choice...
CSS and JavaScript animation performance - Web Performance
tions for more details. in terms of performance, there is no difference between implementing an animation with css transitions or animations. both of them are classified under the same css-based umbrella in this article. requestanimationframe the requestanimationframe() api provides an efficient way to make animations in javascript. the callback function of the method is called by the browser before the next repaint on each frame. compared to settimeout()/setinterval(), which need a specific delay parameter, requestanimationframe() is much more efficient. developers can create an animation by simply changing an element's style each time the loop is called (or updating the canvas draw, or whatever.) note: like css transitions and animations, requestanimationframe() pauses when the current t...
...st cases, the performance of css-based animations is almost the same as javascripted animations — in firefox at least. some javascript-based animation libraries, like gsap and velocity.js, even claim that they are able to achieve better performance than native css transitions/animations. this can occur because css transitions/animations are simply resampling element styles in the main ui thread before each repaint event happens, which is almost the same as resampling element styles via a requestanimationframe() callback, also triggered before the next repaint. if both animations are made in the main ui thread, there is no difference performance-wise. in this section we'll walk you through a performance test, using firefox, to see what animation method seems better overall. enabling fps tools...
...ach repaint event happens, which is almost the same as resampling element styles via a requestanimationframe() callback, also triggered before the next repaint. if both animations are made in the main ui thread, there is no difference performance-wise. in this section we'll walk you through a performance test, using firefox, to see what animation method seems better overall. enabling fps tools before going through the example, please enable fps tools first to see the current frame rate: in the url bar, enter about:config; click 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 upp...
Progressive loading - Progressive web apps (PWAs)
kpwa example a progressive web app: service workers, web manifests, notifications and push. in this article we will go even further and improve the performance of the app by progressively loading its resources. first meaningful paint it's important to deliver something meaningful to the user as soon as possible — the longer they wait for the page to load, the bigger the chance they will leave before waiting for everything to finish. we should be able to show them at least the basic view of the page they want to see, with placeholders in the places more content will eventually be loaded. this could be achieved by progressive loading — also known as lazy loading. this is all about deferring loading of as many resources as possible (html, css, javascript), and only loading those immediately ...
...rsion of the site: mobile, tablet, desktop, print only, etc. it is faster to load all that information as one file rather than many small ones, but if the user doesn't need everything at the very beginning, we could load only what's crucial and then manage other resources when needed. render-blocking resources bundling is a problem, because the browser has to load the html, css, and javascript before it can paint their rendered results onto the screen. during the few seconds between initial website access and completion of loading, the user sees a blank page, which is a bad experience. to fix that we can, for example, add defer to javascript files: <script src="app.js" defer></script> they will be downloaded and executed after the document itself has been parsed, so it won't block renderi...
...— this would improve performance even more, but for the readability of the example we will skip that approach too. images besides javascript and css, websites will likely contain a number of images. when you include <img> elements in your html, then every referenced image will be fetched and downloaded during initial website access. it's not unusual to have megabytes of image data to download before announcing the site is ready, but this again creates a bad perception of performance. we don't need all of the images in the best possible quality at the very beginning of viewing the site. this can be optimized. first of all, you should use tools or services similar to tinypng, which will reduce the file size of your images without altering the quality too much. if you're past that point, then ...
Media - Progressive web apps (PWAs)
ecify the margins separately for @page:left and @page:right. for print media, you normally use appropriate length units like inches (in) and points (pt = 1/72 inch), or centimeters (cm) and millimeters (mm). it is equally appropriate to use ems (em) to match the font size, and percentages (%). you can control how the content of the document breaks across page boundaries, by using the page-break-before, page-break-after and page-break-inside properties. example this rule sets the page margins to one inch on all four sides: @page {margin: 1in;} this rule ensures that every h1 element starts on a new page: h1 {page-break-before: always;} more details for full details of css support for paged media, see paged media in the css specification. like other features of css, printing depends...
... <p>this is the second section...</p> <div id="print-head"> heading for paged media </div> <div id="print-foot"> page: </div> </body> </html> make a new stylesheet, style4.css. ...
...eading for paged media </div> <div id="print-foot"> page: </div> </body> </html> make a new stylesheet, style4.css. ...
Patterns - SVG: Scalable Vector Graphics
Web › SVG › Tutorial › Patterns
here, we've just drawn two rectangle elements inside the pattern (which overlap, and one of which is twice the size of the other and is used to fill in the entire pattern), and one circle. the confusing thing about patterns is defining a unit system and their size. in the example above...
...="url(#gradient2)"/> <circle cx="25" cy="25" r="20" fill="url(#gradient1)" fill-opacity="0.5"/> </pattern> </defs> <rect fill="url(#pattern)" stroke="black" width="200" height="200"/> </svg> screenshotlive sample inside the <pattern> element, you can include any of the other basic shapes you've included before, and each of them can be styled using any of the styles you've learned before, including gradients and opacity. here, we've just drawn two rectangle elements inside the pattern (which overlap, and one of which is twice the size of the other and is used to fill in the entire pattern), and one circle. the confusing thing about patterns 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 describ...
...y. here, we've just drawn two rectangle elements inside the pattern (which overlap, and one of which is twice the size of the other and is used to fill in the entire pattern), and one circle. the confusing thing about patterns is defining a unit system and their size. in the example above, we've defined a width and height attribute on the pattern element to describe how far the pattern should go before it begins repeating itself again. there are also x and y attributes available if you want to offset the start point of this rectangle somewhere within your drawing. the reason they've been used here is described below. as with the gradientunits attribute used above, patterns also have an attribute, patternunits, which specifies the units that these attributes will take. it defaults to "objectbou...
Tutorials
with the language and its syntax, and got some basic experience with using it, its time to dive a bit deeper. this module looks at the cascade and inheritance, all the selector types we have available, units, sizing, styling backgrounds and borders, debugging, and lots more. the aim here is to provide you with a toolkit for writing competent css and help you understand all the essential theory, before moving on to more specific disciplines like text styling and css layout. styling text here we look at text styling fundamentals, including setting font, boldness, and italics, line and letter spacing, and drop shadows and other text features. we round off the module by looking at applying custom fonts to your page, and styling lists and links. common css questions common questions and answe...
...nable, 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 level 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, such as variables, strings, numbers and arrays. javascript building blocks in this module, we continue our coverage of all javascript's key fundamental features, turning our attention to commonly-encountered types of code block such as conditional...
... if you want to go further with your knowledge of the language and write more efficient code, therefore we've provided this module to help you. here we teach object theory and syntax in detail, look at how to create your own objects, and explain what json data is and how to work with it. client-side web apis when writing client-side javascript for websites or applications, you won't go very far before you start to use apis — interfaces for manipulating different aspects of the browser and operating system the site is running on, or even data from other websites or services. in this module, we will explore what apis are, and how to use some of the most common apis you'll come across often in your development work. a re-introduction to javascript a recap of the javascript programming l...
Using custom elements - Web Components
to share a single backing stylesheet. with this optimization the performance of external and internal styles should be similar. customized built-in elements now let's have a look at another customized built in element example — expanding-list (see it live also). this turns any unordered list into an expanding/collapsing menu. first of all, we define our element's class, in the same manner as before: class expandinglist extends htmlulistelement { constructor() { // always call super first in constructor super(); // write element functionality in here ... } } we will not explain the element functionality in any detail here, but you can discover how it works by checking out the source code. the only real difference here is that our element is extending the htmlulistelem...
...ode. the only real difference here is that our element is extending the htmlulistelement interface, and not htmlelement. so it has all the characteristics of a <ul> element with the functionality we define built on top, rather than being a standalone element. this is what makes it a customized built-in, rather than an autonomous element. next, we register the element using the define() method as before, except that this time it also includes an options object that details what element our custom element inherits from: customelements.define('expanding-list', expandinglist, { extends: "ul" }); using the built-in element in a web document also looks somewhat different: <ul is="expanding-list"> ... </ul> you use a <ul> element as normal, but specify the name of the custom element inside the...
...in, you can see the full javascript source code here. using the lifecycle callbacks you can define several different callbacks inside a custom element's class definition, which fire at different points in the element's lifecycle: connectedcallback: invoked each time the custom element is appended into a document-connected element. this will happen each time the node is moved, and may happen before the element's contents have been fully parsed. note: connectedcallback may be called once your element is no longer connected, use node.isconnected to make sure. disconnectedcallback: invoked each time the custom element is disconnected from the document's dom. adoptedcallback: invoked each time the custom element is moved to a new document. attributechangedcallback: invoked each ti...
Using templates and slots - Web Components
is article explains how you can use the <template> and <slot> elements to create a flexible template that can then be used to populate the shadow dom of a web component. the truth about templates when you have to reuse the same markup structures repeatedly on a web page, it makes sense to use some kind of a template rather than repeating the same structure over and over again. this was possible before, but it is made a lot easier by the html <template> element (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 ...
...default text</slot></p> if the slot's content isn't defined when the element is included in the markup, or if the browser doesn't support slots, <my-paragraph> just contains the fallback content "my default text". to define the slot's content, we include an html structure inside the <my-paragraph> element with a slot attribute whose value is equal to the name of the slot we want it to fill. ...
... 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 words, the dom tree from the <element-details> elements get composed together with the content of the shadow root. for both <element-details> elements, an attributes heading gets automatically added from the shadow root before the position of the "attributes" named slot. because the first <element-details> has a <dl> element which explicitly references the "attributes" named slot from its shadow root, the contents of that <dl> replace the "attributes" named slot from the shadow root. because the second <element-details> doesn’t explicitly reference the "attributes" named slot from its shadow root, its content for t...
Index - XSLT: Extensible Stylesheet Language Transformations
Web › XSLT › Index
t bindings dom, javascript, xml, xslt javascript can run xslt transformations through the xsltprocessor object. once instantiated, an xsltprocessor has an xsltprocessor.importstylesheet() method that takes as an argument the xslt stylesheet to be used in the transformation. the stylesheet has to be passed in as an xml document, which means that the .xsl file has to be loaded by the page before calling xsltprocessor.importstylesheet(). this can be done via xmlhttprequest or xmldocument.load(). 11 resources xslt no summary! 12 setting parameters xslt while running transformations using precoded .xsl and .xml files is quite useful, configuring the .xsl file from javascript may be even more useful. for example, javascript and xslt could be used to ...
...sl:attribute-set> element creates a named set of attributes, which can then be applied as whole to the output document, in a manner similar to named styles in css. 23 <xsl:attribute> attribute, element, reference, xslt the <xsl:attribute> element creates an attribute in the output document, using any values that can be accessed from the stylesheet. the element must be defined before any other output document element inside the output document element for which it establishes attribute values. but it may be after or inside elements that won't be part of the output (like <xsl:choose> or <xsl:apply-templates> etc.). 24 <xsl:call-template> element, reference, xslt, call-template the <xsl:call-template> element invokes a named template. 25 <xsl:cho...
..., eventually, newer version) element is not supported. 32 <xsl:for-each> element, reference, xslt, for, for-each the <xsl:for-each> element selects a set of nodes and processes each of them in the same way. it is often used to iterate through a set of nodes or to change the current node. if one or more <xsl:sort> elements appear as the children of this element, sorting occurs before processing. otherwise, nodes are processed in document order. 33 <xsl:if> element, reference, xslt, if the <xsl:if> element contains a test attribute and a template. if the test evaluates to true, the template is processed. in this it is similar to an if statement in other languages. to achieve the functionality of an if-then-else statement, however, use the <xsl:choose> elem...
Content Scripts - Archive of obsolete content
("sdk/page-mod"); pagemod.pagemod({ include: "*.mozilla.org", contentscriptfile: [data.url("jquery.min.js"), data.url("my-content-script.js")] }); if you do this, the scripts can interact directly with each other, just like scripts loaded by the same web page. you can also use contentscript and contentscriptfile together. if you do this, scripts specified using contentscriptfile are loaded before those specified using contentscript. this enables you to load a javascript library like jquery by url, then pass in a simple script inline that can use jquery: // main.js var data = require("sdk/self").data; var pagemod = require("sdk/page-mod"); var contentscriptstring = '$("body").html("<h1>page matches ruleset</h1>");'; pagemod.pagemod({ include: "*.mozilla.org", contentscript: content...
...ion(response) { console.log(response); }); worker.port.emit("my-addon-message", "message from the add-on"); } // content-script.js self.port.on("my-addon-message", handlemessage); function handlemessage(message) { alert(message); self.port.emit("my-script-response", "response from content script"); } the port api see the reference page for the port object. the postmessage api before the port object was added, add-on code and content scripts communicated using a different api: the content script called self.postmessage() to send and self.on() to receive the add-on script called worker.postmessage() to send and worker.on()to receive the api is still available and documented, but there's no reason to use it instead of the port api described here. the exception is the cont...
tabs - Archive of obsolete content
quire("sdk/tabs"); tabs.on('ready', function(tab) { var worker = tab.attach({ contentscript: 'document.body.style.border = "5px solid red";' }); }); parameters options : object optional options: name type contentscriptfile string,array the local file urls of content scripts to load. content scripts specified by this option are loaded before those specified by the contentscript option. optional. contentscript string,array a string or an array of strings of code to be evaluated in the context. content scripts specified by this option are loaded after those specified by the contentscriptfile option. optional. contentscriptoptions object you can use this option to define read-only values f...
... are passed the tab object. persisted : listeners are passed a boolean value indicating whether or not the page was loaded from the bfcache. activate this event is emitted when the tab is made active. note that you cannot guarantee that a tab's content, or even its url, are initialized at the time activate is emitted. this is because when a new tab is opened, its activate event may be emitted before the content is loaded. you can use the tab's readystate property to determine whether the tab's content and url will be available: if readystate is uninitialized or loading, then you can't access the tab's properties and must wait for the tab's ready event. arguments tab : listeners are passed the tab object. deactivate this event is emitted when the tab is made inactive. arguments tab : l...
content/loader - Archive of obsolete content
frame = self._frame = this.element; self._emit('propertychange', { contenturl: self.contenturl }); } })); }, _onchange: function _onchange(e) { if ('contenturl' in e) this._frame.setattribute('src', this._contenturl); } }); loader properties contentscriptfile the 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. this may take one of the following values: "start": load content scripts immediately after the document element for the page is in...
...ontentscript 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. this may take one of the following values: "start": load content scripts immediately after the document element for the page is inserted into the dom, but before the dom content itself has been loaded "ready": load content scripts once dom content has been loaded, corresponding to the domcontentloaded event "end": load content scripts once all the content (dom, js, css, images) for the page has been loaded, at the time the window.onload event fires contentscriptoptions read-only value exposed to content scripts under self.options property. any kind ...
content/worker - Archive of obsolete content
parameters options : object required options: name type window object the content window to create javascript sandbox for communication with. optional options: name type contentscriptfile string,array the local file urls of content scripts to load. content scripts specified by this option are loaded before those specified by the contentscript option. optional. contentscript string,array the texts of content scripts to load. content scripts specified by this option are loaded after those specified by the contentscriptfile option. optional. onmessage function functions that will registered as a listener to a 'message' events. onerror fun...
...l public properties that are listed below. methods postmessage(data) asynchronously emits "message" events in the enclosed worker, where content script was loaded. parameters data : number,string,json the data to send. must be stringifiable to json. destroy() destroy the worker by removing the content script from the page and removing all registered listeners. a detach event is fired just before removal. properties port object that allows you to: send customized messages to the worker using the port.emit function receive events from the worker using the port.on function url the url of the content. tab if this worker is attached to a content document, returns the related tab. events message this event allows the content worker to receive messages from its associated content...
ui/sidebar - Archive of obsolete content
sidebar scripts you can't directly access your sidebar's content from your main add-on code, but you can send messages between your main add-on code and scripts loaded into your sidebar. on the sidebar end of the conversation, sidebar scripts get a global variable addon that contains a port for sending and receiving messages. on the add-on side, you need to get a worker object for the sidebar before you can send or receive messages. there are two events emitted by the sidebar which will give you a worker: attach and ready. listen to attach if the first message in your add-on goes from the sidebar scripts to the main add-on code, and listen to ready if the first message goes from the main add-on code to the sidebar script. using attach the attach event is triggered whenever the dom for a n...
...l (typically, loaded from the "data" folder using self.data.url()). from firefox 34, you can use "./myfile.html" as an alias for self.data.url("myfile.html"). optional options: name type id string the id of the sidebar. this used to identify this sidebar in its chrome window. it must be unique. this option was mandatory before firefox 28. onattach function listener for the sidebar's attach event. ondetach function listener for the sidebar's detach event. onshow function listener for the sidebar's show event. onhide function listener for the sidebar's hide event. sidebar the sidebar object. once a sidebar has...
Using third-party modules (jpm) - Archive of obsolete content
this tutorial you'll need to have installed jpm and learned the basic jpm commands. to install menuitem you'll need to have git command. if you have error related to git, check you have latest git command installed. the add-on sdk is extensible by design: you can use the modules that ship inside firefox, but you can also create your own modules and make them available for anyone else to use. before the jpm tool was available, there wasn't any package manager for these community-developed modules, so it wasn't obvious where to find community-developed modules, or how to install and update them. with jpm, we use npm as the package manager for sdk modules that don't ship inside firefox. module developers can publish sdk modules to npm, and add-on developers can install them from npm and build...
... menuitem package.json test we're interested in using the "menuitem" module, which is at "addon-pathfinder/lib/ui/menuitem". open "index.js" and replace it with this: var menuitems = require("menuitem"); var menuitem = menuitems.menuitem({ id: "clickme", menuid: "menu_toolspopup", label: "click me!", oncommand: function() { console.log("clicked"); }, insertbefore: "menu_pageinfo" }); now run the add-on: jpm run -b nightly you should see a new menu item in the tools menu labeled "click me!". click the button, and the message "clicked" is logged. note: in more recent versions of firefox, the menu bar may not be visible by default. to show the menu bar, click on the open menu icon and select "customize". then, under show / hide toolbars, enable the menu ...
Miscellaneous - Archive of obsolete content
alse); } } function onfocusinput(focusevent) { focusedcontrol = focusevent.originaltarget; } function onblurinput(blurevent) { focusedcontrol = null; } or var element = document.commanddispatcher.focusedelement; inserting text at the cursor function inserttext(element, snippet) { var selectionend = element.selectionstart + snippet.length; var currentvalue = element.value; var beforetext = currentvalue.substring(0, element.selectionstart); var aftertext = currentvalue.substring(element.selectionend, currentvalue.length); element.value = beforetext + snippet + aftertext; element.focus(); //put the cursor after the inserted text element.setselectionrange(selectionend, selectionend); } inserttext(document.getelementbyid("example"), "the text to be inserted"); disa...
...reateinstance(ci.nsibinaryinputstream); stream.setinputstream(postdata); var postbytes = stream.readbytearray(stream.available()); var poststr = string.fromcharcode.apply(null, postbytes); //do anything to your poststr alert(poststr); getting a string from the input stream is made somewhat simpler in firefox 4, by the addition of netutil.readinputstreamtostring() getting postdata of a request before the request is sent the above code will get the postdata for a page that has already loaded. to see what the postdata looks like before the request is even sent, use the 'http-on-modify-request' observer topic: observerservice.addobserver(observer, 'http-on-modify-request', false); where "observer" is an object that has a method "observe": function observe(subject, topic, data) { subject.qu...
Preferences - Archive of obsolete content
s whether the preference has been changed from the default value. if so, it will return true, otherwise false. in particular, when no default value exists for a preference, prefhasuservalue() indicates whether a preference exists. attempting to read a nonexistent preference using one of the get*pref methods will throw an exception. using prefhasuservalue() lets you check if the preference exists before attempting to read it. for example: if (prefs.prefhasuservalue("mypref")) { alert(prefs.getcharpref("mypref")); } note that the getcharpref() call may throw error even if the preference exists, for example if it has a different type. as of firefox 54, you can pass a default value as the second argument to any get*pref method. the default value will be returned if the preference doesn't exis...
...ing to branch.setcharpref etc. ...
Rosetta - Archive of obsolete content
obaton = document.createcomment(" the previous code has been automatically translated from \"" + smimetype + "\" to \"text/ecmascript\". ...
...t.attributes, nattr = 0; nattr < aattrs.length; nattr++) { ocompiled.setattribute(aattrs[nattr].name, aattrs[nattr].value); } ocompiled.type = "text\/ecmascript"; if (oxhr200) { ocompiled.src = "data:text\/javascript," + encodeuricomponent(odicts[smimetype](oxhr200.responsetext)); } ocompiled.text = oxhr200 ? ...
Toolbar - Archive of obsolete content
id of the toolbar to install to. * @param {string} id the id of the button to install. * @param {string} afterid the id of the element to insert after. ...
...l */ function installbutton(toolbarid, id, afterid) { if (!document.getelementbyid(id)) { var toolbar = document.getelementbyid(toolbarid); // if no afterid is given, then append the item to the toolbar var before = null; if (afterid) { let elem = document.getelementbyid(afterid); if (elem && elem.parentnode == toolbar) before = elem.nextelementsibling; } toolbar.insertitem(id, before); toolbar.setattribute("currentset", toolbar.currentset); document.persist(toolbar.id, "currentset"); if (toolbarid == "addon-bar") toolbar.collapsed = false; } } if (firstrun) { installbutton("nav-bar", "my-extension-navbar-button"); // the "addon-bar" is available since ...
How to convert an overlay extension to restartless - Archive of obsolete content
read arbitrary binary data, of various sizes, in an endian-safe way, is to use dataview. the other typed array stuff is viable in firefox 4+. this wasn't added until firefox 15. if you were using nsibinaryinputstream or anything similar, figuring out dataview will be fairly straightforward. just read the docs and it's pretty simple. it will probably be notably faster than whatever you were doing before. reportedly xmlhttprequest doesn't work reliably when used in jsm under versions of firefox less than 16, however as previously mentioned, this guide should be taken as requiring firefox 17+. step 4: manually handle default preferences normal extensions load default preferences from a standardized file automatically. restartless extensions don't (for no good reason). this part is fairly easy t...
...add-on is via bootstrap.js:startup() rather than a "load" handler in a xul overlay. your localization handling should be unaffected by your transition to a restartless/extractionless add-on so long as you properly clear the chrome cache on add-on shutdown and load your properties files using the method listed above. your property files and dtd files loaded from chrome:// uris should work just as before. this is all assuming a minimum version of firefox 17+ (or other gecko 17+ application) which you should remember to state explicitly in your install.rdf. just remember that whatever you start you also need to have the ability to undo. in order for your add-on to reliably update without a restart it needs to be able to shutdown/disable cleanly. also note that once you do get this all up and run...
Listening to events in Firefox extensions - Archive of obsolete content
ched when the user has navigated away from the page. pageshow dispatched when a page is newly displayed. pagehide dispatched when a page is hidden. standard behavior for web pages is: user navigates to a page. as the page loads, inline scripts run. once the page is loaded, the onload handler fires. some pages include a fourth step. if a page uses an unload or beforeunload handler, it fires when the user navigates away from the page. if an unload handler is present, the page will not be cached. when a user navigates to a cached page, inline scripts and the onload handler do not run (steps 2 and 3), since in most cases, the effects of these scripts have been preserved. if the page contains scripts or other behaviors that fire during loading that you want to ...
... browser. when this property is set to false, the unload handler, if present, fires immediately after the pagehide event. firefox 1.5 tries to simulate load events in the same order they would occur when the page is initially loaded. frames are treated the same way as the top-level document. if the page contains frames, then when the cached page is loaded: pageshow events from each frame fire before the pageshow event in the main document fires. when the user navigates away from the cached page, the pagehide 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 d...
Appendix A: Add-on Performance - Archive of obsolete content
ure that they minimize their add-ons' performance impact, and here are a few simple guidelines that should be followed to achieve that. startup this is the area where add-ons have the most noticeable impact. most add-ons use the load event handler in the main overlay to initialize their objects and sometimes read files or even fetch remote data. the problem with the onload event is that it runs before the main window becomes visible, so all handlers need to complete before the user can see the window. an add-on can normally add a few hundred milliseconds to startup time because of the load handler, and it's not hard to figure out what having several add-ons will do. luckily, minimizing your startup time is easy, if you follow these guidelines: do not load or run code before it’s needed. ...
...nd a remove function. don't forget to remove what you don't need anymore! even if you need something during the whole existence of the window, you should clean everything up in the unload event handler. even the unload event should be handled efficiently. even if it is not as important as other areas, firefox shutdown can also be slowed down because of add-ons. if there's anything you can unload before shutdown, or if there's anything you can do to unload things more efficiently, then it's important that you do. never use xmlhttprequest in synchronous mode. if your add-on needs to perform a heavy operation like sorting or a complex mathematical calculation, you should use dom workers to offload the work to other threads. ...
Appendix C: Avoiding using eval in Add-ons - Archive of obsolete content
rent and administer yourself, there is a huge security risk, because of, but not limited to: you might discontinue your project or sell it, so that it is possible another person with malicious intentions takes over your domain. the server and/or domain name might be compromised. if using an unencrypted, insecure connection, a man-in-the-middle attacker might replace the json with attack code before it arrives at the user. use native json since firefox 3.5 you should use json. really, just use it! note: do not use json parsers implemented in javascript. these implementations are less efficient and often also contain serious security vulnerabilities. such implementations are meant to be used within a very different security context, namely a website, where the origin of the data is usuall...
...al function which you then call from the new one. // wrap in an anonymous function (which is called immediately). // this will encapsulate local variables such as _original and // not pollute the global namespace. (function() { // keep a reference to the original function. var _original = gbrowser.addtab; // override a function. gbrowser.addtab = function() { // execute some action before the original function call. try { myaddon.onaddtab(arguments[0]); } catch (ex) { /* might handle this */ } // execute original function. var rv = _original.apply(gbrowser, arguments); // execute some action afterwards. try { myaddon.doneaddtab(rv); } catch (ex) { /* might handle this */ } // return the original result return rv; }; })(); t...
Connecting to Remote Content - Archive of obsolete content
se as text. if the response is an xml document, the responsexml property will hold an xmldocument object that can be manipulated using dom methods. sometimes the server doesn't specify an xml content-type header, which is necessary for the xml parsing to happen automatically. you can use overridemimetype to force the response to be parsed as xml. request.overridemimetype("text/xml"); // do this before sending the request! the open method takes two required parameters: the http request method and the url to send the request. the http request method can be "get", "post" or "put". sending a post request requires you to set the content type of the request and to pass the post data to the send() method as below. request.open("post", url, true); request.setrequestheader("content-type", "applicati...
...sidebar > tamper data once you open the tamper data view, all requests and responses will begin to appear in it. you can discover some interesting things about firefox like this, such as the automatic update urls for extensions, and the behavior of web applications such as gmail. if you click on the "start tamper" button, for every request made you will get a popup dialog for tampering with it before it is sent. you can use it to view or even modify the data in a request, and then inspect the result. this can be a lot of work because there is a lot of web activity in a normal firefox window, so use it sparingly. a tutorial on tamper data can be found here. note: you should always test your connection code to cover edge cases, like when there is no internet connection, or the computer is con...
Getting Started with Firefox Extensions - Archive of obsolete content
nown as jetpacks), bootstrapped extensions and traditional extensions. if you're only getting started developing add-ons, the add-ons sdk provides a great way to quickly create simple ones and build on them. this tutorial focuses on traditional extensions, which are created differently. bootstrapped extensions are a step above traditional ones in complexity, so you should go through this tutorial before giving them a try. we'll begin the tutorial by analyzing a very simple extension. the hello world extension our sample extensions and this tutorial in general are meant for modern versions of firefox, but most of it works on older versions too. we'll now begin with a basic "hello world" extension. let's start by installing it. click on the link below. note: this extension is unsigned. starti...
... very simple extension. the hello world extension our sample extensions and this tutorial in general are meant for modern versions of firefox, but most of it works on older versions too. we'll now begin with a basic "hello world" extension. let's start by installing it. click on the link below. note: this extension is unsigned. starting with firefox 43, extensions need to be signed by mozilla before they can be installed in firefox. unsigned add-ons can still be installed in developer edition, nightly, and esr versions of firefox, after toggling the xpinstall.signatures.required preference in about:config. install hello world click the above link and then click "allow" in the pop-up bubble. you should see another pop-up telling you that you are installing an unverified add-on. click "insta...
JavaScript Object Management - Archive of obsolete content
at much. if you have complex behavior that requires too much code, look for ways to divide it into multiple objects and files. you can include as many scripts in a xul window as you need. to initialize your chrome objects, it's usually better to run the initialization code from the "load" event handler for the window. the load event is fired after the dom on the window has loaded completely, but before it's displayed to the user. this allows you to manipulate and possibly change elements in the window without the user noticing the changes. /** * controls the browser overlay for the hello world extension. */ 〈namespace〉.browseroverlay = { /** * initializes this object. */ init : function(aevent) { this._stringbundle = document.getelementbyid("xulschoolhello-string-bundle")...
..."xulschoolhello-string-bundle"); // you can make changes to the window dom here. } // more stuff }; window.addeventlistener( "load", function() { 〈namespace〉.browseroverlay.init(); }, false); there are some things you can't (or shouldn't) do inside load handlers, such as closing the window being loaded, or opening new windows, alerts or dialogs. the window has to finish loading before it can do any of these things. they are bad ui practices anyway and you should avoid them. if you really need to do something like this anyway, one way to do it is to have a timeout execute the code after a delay: init : function(aevent) { let that = this; this._stringbundle = document.getelementbyid("xs-hw-string-bundle"); window.settimeout( function() { window.alert(that._st...
User Notifications and Alerts - Archive of obsolete content
« previousnext » it is often the case that extensions need to notify users about important events, often requiring some response. using modal dialogs and alerts is usually a bad idea. they interrupt the user's workflow, demanding immediate action before anything else can be done. 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. this section lists a few alternatives that give you the possibility of notifying the user and requesting action without being too annoying. the notificationbox element you have probably seen these before. the "remember password" prompt is the one that shows up the most often. they are thin boxes that appear from beneath the tab list ...
...ated, given the advantages of xul overlays and css positioning. however, these solutions are prone to be buggy and have accessibility issues. you should use the 2 alternatives mentioned above whenever possible. if none of those fit your needs then this is an acceptable solution. an easy way to display alerts is to include a hidden box in your overlay, which you can fill with any content you need before removing the hidden attribute so that it is displayed to the user. the best locations for this kind of box are above and below the tab browser. below is preferrable because it only cuts the bottom part of the current page, as opposed to pushing down all tabs and content. notification boxes are a good guideline to what you should aim for: thin, informative and easy to dismiss. another option is t...
Setting up an extension development environment - Archive of obsolete content
nnection = false. this prevents the browser debugger from prompting for connection permission every time. extensions.logging.enabled = true. this will send more detailed information about installation and update problems to the error console. (note that the extension manager automatically restarts the application at startup sometimes, which may mean you won't have time to see the messages logged before the automatic restart happens. to see them, prevent the automatic restart by setting the environment no_em_restart to 1 before starting the application.) nglayout.debug.disable_xul_fastload = true. for gecko 2.0+ (firefox 4.0+). see this bug for more information. although the bug has been closed, it is believed that this pref is still relevant. you might also want to set dom.report_all_js_excep...
...ith no curly brackets {}. the contents of this file should be the path to the directory that contains your install.rdf file, for example /full/path/to/yourextension/ on mac and linux, and c:\full\path\to\yourextension\ on windows. remember to include the closing slash and remove any trailing whitespace. note: if you already installed the extension via xpi, you should uninstall it first before creating the pointer file. also note that the use of proxy files requires that the extension's chrome.manifest defines its chrome urls using traditional directories, rather than a jared structure. see below. place the file in the extensions folder of your profile and restart the application. using directories rather than jars regardless of whether you choose to eventually package your...
An Interview With Douglas Bowman of Wired News - Archive of obsolete content
ontent inside tables. the sheer amount [sic] of redundant <font> tags inside every cell was probably enough to double file size. my initial attempts at the markup and css for the wired news design eliminated the majority of our tables, but left one master table to control the primary columns of each page. ...
... by eliminating tables that were strictly used for layout, we significantly cut back on the amount of markup and useless tags in our html, and gained a structure that is much easier to maintain. ...
Creating reusable content with CSS and XBL - Archive of obsolete content
plications where parts need to be self-contained and reusable. you can place stylesheets in separate files, and you can place scripts in separate files. but you must link those files from the document as a whole. another structural limitation concerns content. you can use css to provide content for selected elements, but the content is limited to text and images, and its positioning is limited to before or after the selected element. mozilla provides a mechanism that overcomes these limitations: xbl (xml bindings language). you can use xbl to link selected elements to their own: stylesheets content properties and methods event handlers because you avoid linking everything at the document level, you can make self-contained parts that are easy to maintain and reuse. more details ...
... and paste the content from here: /*** xbl demonstration ***/ [anonid="square"] { width: 20em; height: 20em; border: 2px inset gray; } [anonid="button"] { margin-top: 1em; padding: .5em 2em; } open the document in your browser and press the button. this wiki does not support javascript in pages, so it is not possible to show the demonstration here. it looks something like this, before and after you press the button: notes about this demonstration: the html document links the document stylesheet as usual, but it does not link any javascript code. the document does not contain any buttons. it only contains the text of the button's label. the button is added by the binding. the document stylesheet links the binding. the binding links its own stylesheet, a...
XML data - Archive of obsolete content
<name>pacific</name> <area>180,000</area> <depth>4,000</depth> </ocean> <ocean> <name>indian</name> <area>75,000</area> <depth>3,900</depth> </ocean> <ocean> <name>southern</name> <area>20,000</area> <depth>4,500</depth> </ocean> </planet> make a new css file, style9.css. ...
...: 200%; content: "oceans"; margin: -.75em 0px .25em -.25em; padding: .1em .25em; background-color: #cdf; } planet { display: block; margin: 2em 1em; border: 4px solid #cdf; padding: 0px 1em; background-color: white; } ocean { display: block; margin-bottom: 1em; } name { display: block; font-weight: bold; font-size: 150%; } area { display: block; } area:before { content: "area: "; } area:after { content: " million km\b2"; } depth { display: block; } depth:before { content: "mean depth: "; } depth:after { content: " m"; } open the document in your browser: oceans arctic area: 13,000 million km² mean depth: 1,200 m atlantic area: 87,000 million km² mean depth: 3,900 m ...
CSS3 - Archive of obsolete content
e[attribute$="value"], e[attribute*="value"] . new pseudo-classes: :target, :enabled and :disabled, :checked, :indeterminate, :root, :nth-child and :nth-last-child, :nth-of-type and :nth-last-of-type, :last-child, :first-of-type and :last-of-type, :only-child and :only-of-type,:empty, and :not. pseudo-elements are now characterized by two colons rather than one: :after becomes ::after, :before becomes ::before, :first-letter becomes ::first-letter, and :first-line becomes ::first-line. the new general 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. media queries recommendation since june 19th, 2012 extends the form...
...-rules inside @media and the adding of a new css at-rule, @supports, and a new dom method css.supports(). css multi-column layout module working draft adds support for easy multi-column layouts using the css columns, column-count, column-fill, column-gap, column-rule, column-rule-color, column-rule-style, column-rule-width, column-span, column-width, break-after, break-before, and break-inside. css values and units module level 3 candidate recommendation makes initial and inherit keywords usable on any css property. formally defines the css data types of css 2.1, that were implicitely defined by their grammar token and some textual precisions. adds: definition for new font-relative length units: rem and ch . d...
Notes on HTML Reflow - Archive of obsolete content
geometry of elements that are earlier "in the flow", so layout can proceed left-to-right, top-to-bottom through the document. there are exceptions to this rule: most notably, html tables may require more than one pass. the xul box 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. all html reflow, including the initial reflow , begins at the root frame , which corresponds to the <html> element of the html document. reflow proceeds recursively through some or all of the frame hierarchy, computing geometric information for each frame object th...
... when content streams in from the network. incremental reflows are queued by the presentation shell for batched dispatch. reflow state the reflow state object, nshtmlreflowstate, is used to pass constraining information "down" from parent frames to child frames. for example, a <div> with a constrained width (e.g., set via the css width property) would note this in the reflow state object before flowing its children. when reflow begins, the root reflow state is initialized with information about the top-level container for the document's presentation; e.g., the width and height of the application window. this is passed as an argument to the reflow method of the root frame in the frame hierarchy. each container frame constructs a new reflow state object (based on ...
Autodial for Windows NT - Archive of obsolete content
el | network connections | advanced | dialup preferences is set to enable autodial, then any application trying to access the internet will trigger the autodial feature whenever an internet address cannot be reached. however, this service will won't function if you have a lan card installed, unless that particular address has been accessed in the past via a dialup connection. origin of the bug before the implementation of the autodial helper feature, mozilla would trigger the autodial feature on nt-based operating systems, but only if certain conditions are met. these conditions are as follows: the autodial service is running control panel | network connections | advanced | dialup preferences | enable autodial by location is set for some location a dialup connection has been configured t...
...ult connection". these two behave the same for mozilla, and trigger autodial when you fail to reach a requested address. issues there have been a few bug reports filed against this new feature that are the result of the fact that mozilla now looks at the control panel | internet options | connections settings. some users have had the autodial setting turned on, but mozilla never triggered them before. starting in mozilla 1.1, autodial is triggered whenever an address can't be reached (mozilla now mimics the remote access autodial service.) see bug 160846, bug 167624, and bug 160846. if a user doesn't want the os to use autodial, he must turn off the feature from the os. there is also a problem with the aol client when used as a dialer. bug 166134 describes how the aol client installs itself a...
Kill the XUL.mfl file for good - Archive of obsolete content
r in a fileserver based environment, this can be problematic: at several megabytes a pop, these files will take up a considerable amount of space, because each user has his own... loading these files from the server, and storing them back slows down the network, thus it may actually be faster without than with xul.mfl occasionnally gets corrupted, needing a manual intervention to wipe it out, before mozilla again works correctly. with quicklauncer (see above), mozilla's speed is actually quite adequate, even without xul.mfl for these reasons, it is desirable to disable the xul.mfl functionality. unfortunately, there appears to be no "clean" way of doing so (javascript command in prefs.js or registry setting). but creating a subdirectory named xul.mfl in mozilla's profile directory seems to...
...ve), mozilla's speed is actually quite adequate, even without xul.mfl for these reasons, it is desirable to disable the xul.mfl functionality. unfortunately, there appears to be no "clean" way of doing so (javascript command in prefs.js or registry setting). but creating a subdirectory named xul.mfl in mozilla's profile directory seems to help (mozilla is not smart enough to remove the directory before creating the file, thus the presence of the directory effectively disables this (mis)feature). n.b. it seems that as of version 1.5, the xul.mfl file no longer is a problem, so this part may be skipped if you have a recent enough mozilla version. ...
Getting Started - Archive of obsolete content
skin\classic\messenger messenger contains styles of the mail client. skin\classic\messenger-newsblog messenger-newsblog contains the only css file. skin\classic\mozapps mozapps contains all the styles and icons for the browser peripherals, such as the extension manager or update wizard. skin\classic\navigator navigator contains some icons and styles for all sm components. install your new theme before you can see the changes you make to a seamonkey theme (since live edits are restrictively difficult to set up) you must first learn how to repackage the classic theme to make it installable. for the sake of this discussion we will call your theme "my_theme", though you can replace that with any name. copying the necessary files the first step is to move all the files into the right directory stru...
...nd replace them with the name of your theme. the packages section lists which components of the browser you're modifying. if we also had skins for chatzilla, we would need to add another line resembling the other ones and change it to point to chatzilla. but this list includes everything that we changed, so just modify the blue text to point to match the name/version that you used in the sections before this. skin global my_theme jar:chrome/my_theme.jar!/global/ skin mozapps my_theme jar:chrome/my_theme.jar!/mozapps/ skin messenger my_theme jar:chrome/my_theme.jar!/messenger/ skin messenger-newsblog my_theme jar:chrome/my_theme.jar!/messenger-newsblog/ skin communicator my_theme jar:chrome/my_theme.jar!/communicator/ skin help my_theme jar:chrome/my_theme.jar!/help/ skin navigator my_theme jar:c...
Getting Started - Archive of obsolete content
as the css files. to make a change, just replace one of the images with one of your own. it should probably be of the same size, but it doesn't have to be. if you do need to change the size, also make sure to change any css that may be affected by that change. after you've changed the images, launch mozilla and you should see them. creating the install script getting it ready for the installation before we can package everything up for installation, we need to remove all references to classic. copy everything in \mozilla\chrome\classic\skin\classic to a directory called \myskin. skin info when switching skins in mozilla, it displays a preview image and some information about the theme. this is what we're going to create now. take a screenshot of mozilla running your theme and create an image tha...
...png/preview.jpg/preview.gif here the packages section lists which components of the browser suit that you are modifying. if we also had skins for chatzilla, we would have to add another line resembling the other ones and change it to point to chatzilla. but this list includes everything that we changed, so just modify the blue text to point to match the name/version that you used in the sections before this. <rdf:li resource="urn:mozilla:skin:myskin/1.0:communicator"/> <rdf:li resource="urn:mozilla:skin:myskin/1.0:editor"/> <rdf:li resource="urn:mozilla:skin:myskin/1.0:global"/> <rdf:li resource="urn:mozilla:skin:myskin/1.0:messenger"/> <rdf:li resource="urn:mozilla:skin:myskin/1.0:navigator"/> finally, in the last section of the contents.rdf file we need to tell mozilla what version this skin...
Creating a Skin for Firefox/Getting Started - Archive of obsolete content
l global contains almost all of the important css files that define the appearance of the browser. this is the most critical directory in a theme. skin\classic\help help contains all the files for theming the help dialog window. skin\classic\mozapps mozapps contains all the styles and icons for the browser peripherals, such as the extension manager or update wizard. install your new theme before you can see the changes you make to a firefox theme (since live edits are restrictively difficult to set up) you must first learn how to repackage the classic theme to make it installable. for the sake of this discussion we will call your theme "my_theme", though you can replace that with any name. copying the necessary files the first step is to move all the files into the right directory stru...
...d replace them with the name of your theme. the packages section lists which components of the browser you're modifying. if we also had skins for chatzilla, we would need to add another line resembling the other ones and change it to point to chatzilla. but this list includes everything that we changed, so just modify the blue text to point to match the name/version that you used in the sections before this. <rdf:li resource="urn:mozilla:skin:my_theme:communicator"/> <rdf:li resource="urn:mozilla:skin:my_theme:editor"/> <rdf:li resource="urn:mozilla:skin:my_theme:global"/> <rdf:li resource="urn:mozilla:skin:my_theme:messenger"/> <rdf:li resource="urn:mozilla:skin:my_theme:navigator"/> save the file and exit the text editor. install.rdf make a copy of install.rdf and place it in the my_them...
Creating regular expressions for a microsummary generator - Archive of obsolete content
rs appear in a url, and we want to match them in a regular expression, we have to escape them in the expression by prepending them with a backwards slash (\). here's a regular expression that matches our example url: http://cgi\.ebay\.com/ws/ebayisapi\.dll\?viewitem&item=280018439106 it looks almost the same as the url. the only difference is that the regular expression has backwards slashes before the periods and the question mark, since both of those characters have special meaning in regular expressions. matching from the start of the url while this expression matches the url, it also matches other urls that contain this url in their query parameters, for example: http://www.example.com/redirect.php?url=http://cgi.ebay.com/ws/ebayisapi.dll?viewitem&item=280018439106 that's probably...
...ery parameters in any order. but ebay uses a different style of url in some cases (f.e. on its search results page). here's a url for the same item in that different style: http://cgi.ebay.com/mozilla-firefox-logo-1-inch-pin-badge-button-browser_w0qqitemz280018439106qqihz018qqcategoryz2036qqcmdzviewitem to accommodate these urls, we can create a second regular expression that matches them. as before, we should distinguish the components of the url which are unique to the item from those which are common to all auction item urls of this style. here are several other urls of this style: http://cgi.ebay.com/firefox-2002-dvd_w0qqitemz130017517168qqihz003qqcategoryz617qqcmdzviewitem http://cgi.ebay.com/ahm-ho-scale-firefox-tank-car_w0qqitemz290019763032qqihz019qqcategoryz19130qqcmdzviewitem ...
Dehydra Function Reference - Archive of obsolete content
bject representing the function being processed body is an array of {loc:, statements:array of variable types} representing an outline of the function stripped down to variables, function calls and assignments. process_decl(decl) process_decl is called for every global variable, function, or template declaration. decl is a variable type input_end() called once at the end of the c++ source file before the compiler quits. this is useful for finalizing analyses. builtin functions the following functions are provided by dehydra and may be called by the user: print(msg) print a string to stdout (or stderr if the compiler is piping output). if the current callback is associated with a particular location, the location will be printed first. msg is a string to output to customize the location info...
...is is useful for finalizing analyses. builtin functions the following functions are provided by dehydra and may be called by the user: print(msg) print a string to stdout (or stderr if the compiler is piping output). if the current callback is associated with a particular location, the location will be printed first. msg is a string to output to customize the location info printed set this._loc before calling print() include(file [, namespace]) include a javascript file into a namespace. file is a string representing the file to include optional: namespace is an object to include the file into. the default namespace is this the directories in sys.include_path are searched for the file, and the current working directory is searched last. includes are guarded so a file is only included once an...
Exception logging in JavaScript - Archive of obsolete content
this had the unintended consequence of logging "expected" errors at length into the console. ...
...o the c++ in frame 3. no exception will be logged to the error console in this case. that c++ may handle the error, generate a different error, or simply pass it straight back to the js in frame 2. if the javascript in frame 2 either receives an exception from frame 3 or generates its own exception, and that exception remains unandled, then the exception will always be logged to the error console before control returns to the c++ in frame 1. in other words, all unhandled javascript exceptions (except those in rules 3 and 4 above) will be logged before control returns to the outermost c++ caller. forcing logging of exceptions in inner js frames sometimes you might actually want to see all exceptions from inner javascript frames logged (in the call chain above that would be when an exception is un...
Downloading Nightly or Trunk Builds - Archive of obsolete content
o mozilla 1.9.2. however, the numbers are not used all of the time. sometimes the firefox releases are described by a code name. for example "shiretoko" is used for firefox 3.5. and very often neither names nor numbers are used, but rather special words indicating relative order are used. the three common cases are "trunk", meaning the most recent version of mozilla; "branch", meaning the version before trunk (though it can be any version before trunk); and "next", meaning a possible version in the future. so, if you are looking for the cutting edge firefox, you probably want a mozilla branch nightly build, that is, look for a mozilla thing (not a firefox thing), not the breaky one on trunk, but the most recent branch, and built very fresh (last night!), so you can install it. for firefox 3.5 t...
...able passes a certain more-or-less fixed set of tests. nightly builds. the same machines produce about every 24 hours a "nightly" build which can be downloaded by anyone if you know where to get it: these are the nightly builds, and testers all over the world download them and test them, reporting as they go along on any bugs that hit them. anyone can be a tester, you don't need to get approval before you can start testing. when people talk of "nightlies", they often mean "trunk nightlies", though there exist also "branch nightlies" which are somewhat less buggy but also not as "newest & greatest". for instance, one may use a thunderbird "branch nightly" as one's main e-mail client. note that nightly builds may not be created for every platform for every night. if one has questions about the ...
Repackaging Firefox - Archive of obsolete content
notice: the article is about repackaging firefox 2.0 and is obsolete when working on 3.x repackaging. firefox can be customized for the needs of a particular group of users (for example, your organization's employees or clients). because firefox is designed from the ground up for extensibility and customization, this process is simple and easy to maintain. important legal considerations before you get started, it is very important to know and abide by the legal requirements for distributing firefox. you must have written authorization from mozilla to distribute a modified version of firefox. to do this, please contact trademarks@mozilla.com. getting started now, on to the technical details. the following diagram represents an overview of the process and the pieces involved: you wi...
... ...
jspage - Archive of obsolete content
ext":"textcontent"}; var b=["compact","nowrap","ismap","declare","noshade","checked","disabled","readonly","multiple","selected","noresize","defer"];var k=["value","type","defaultvalue","accesskey","cellpadding","cellspacing","colspan","frameborder","maxlength","readonly","rowspan","tabindex","usemap"]; b=b.associate(b);hash.extend(e,b);hash.extend(e,k.associate(k.map(string.tolowercase)));var a={before:function(m,l){if(l.parentnode){l.parentnode.insertbefore(m,l); }},after:function(m,l){if(!l.parentnode){return;}var n=l.nextsibling;(n)?l.parentnode.insertbefore(m,n):l.parentnode.appendchild(m);},bottom:function(m,l){l.appendchild(m); },top:function(m,l){var n=l.firstchild;(n)?l.insertbefore(m,n):l.appendchild(m);}};a.inside=a.bottom;hash.each(a,function(l,m){m=m.capitalize();element.implement("...
...s;}if(!a){for(var b in c){this.cloneevents(d,b); }}else{if(c[a]){c[a].keys.each(function(e){this.addevent(a,e);},this);}}return this;}});element.nativeevents={click:2,dblclick:2,mouseup:2,mousedown:2,contextmenu:2,mousewheel:2,dommousescroll:2,mouseover:2,mouseout:2,mousemove:2,selectstart:2,selectend:2,keydown:2,keypress:2,keyup:2,focus:2,blur:2,change:2,reset:2,select:2,submit:2,load:1,unload:1,beforeunload:2,resize:1,move:1,domcontentloaded:1,readystatechange:1,error:1,abort:1,scroll:1}; (function(){var a=function(b){var c=b.relatedtarget;if(c==undefined){return true;}if(c===false){return false;}return($type(this)!="document"&&c!=this&&c.prefix!="xul"&&!this.haschild(c)); };element.events=new hash({mouseenter:{base:"mouseover",condition:a},mouseleave:{base:"mouseout",condition:a},mousewheel:{...
Modularization techniques - Archive of obsolete content
return ns_nointerface. reference counting is performed using the addref() and release() methods. an objects reference count generally starts at zero. addref() increments that reference count, and release() decrements it. if a call to release() causes the reference count to hit zero, the object will generally free itself. a successful queryinterface() will call addref() on the requested interface before returning. both addref() and release() return the resulting reference count. the convenience macros ns_addref() and ns_release() are preferred over calling addref and release directly. in debug builds, these macros provide useful reference counting logs. use them wherever possible. /* * the nsisupports interface */ class nsisupports { public: ns_imethod queryinterface(const nsiid &aiid, ...
...es. a simple program called regfactory.exe (on windows) or regfactory (on unix) can be used to register self-registering dlls. reference counting basics reference counting is a critical part of modularity picture. there are a number of basic reference counting rules to remember. here's a quick summary. out parameters functions that return a new interface should call addref() on that interface before returning it. nsresult getfoo(ifoo **afoores) { if (afoores == null) { return ns_error_null_pointer; } *afoores = mfoo; ns_addref(*afoores); return ns_ok; } remember that this applies to the interfaces returned by queryinterface(), createinstance() and ns_newx(), and you must call release() on them when you are done to avoid memory leaks. in parameters and local pointers inter...
Scripting - Archive of obsolete content
prism allows for some client-side web application customization. the web application bundle is allowed to hold a javascript file named webapp.js (called the webapp script). this file will be loaded into the prism chrome window very much like a firefox extension is loaded into the browser chrome window. it can contain the following functions: startup when the app starts, before the user interface is displayed. since the web application has not yet loaded, the window object is still undefined. preload just before the user interface is displayed. returning false causes the application to terminate. load after the main application windows has finished loading. the window object has been initialized and can be used. error if there is an error loading the main app page (e.g. the server is no...
... prism exposes desktop integration features through an property of the window object called platform. the platform property implements the nsiplatformglue interface, whose methods are described in the following section. ...
Frequently Asked Questions - Archive of obsolete content
ug. if you have any problems with the bug database feel free to contact contact us. can i use a plugin for svg instead of mozilla's native support? individuals can choose to use a plugin to view svg in mozilla on their own computers, but there is no way for svg content authors to make mozilla use a plugin when people view the svg files on their website. the native svg support must be turned off before mozilla will look to see if there's an svg plugin installed. this is done by toggling a hidden user configuration preference (pref). to access the pref type about:config into the url bar, then type svg.enabled into the filter field. when you double click on the pref you will see its value change to and from true/false, turning the native support on/off. how does mozilla's svg implementation comp...
...hings you should still feel free to ask us friendly questions and give us constructive feedback. who's currently working on what? other than reviewing patches and fixing the occassional bug, alex is currently taking a break from active svg development to concentrate on 'real work' and cool stuff like xtf and jssh. tim is working on implementing <filter> and working on items that need to be done before turning on svg by default. after recently implementing gradients, scooter is working on fixing some issues that remain outstanding and fixing <switch>. jonathan is working on various bugs, especially those that need to be fixed before svg can be enabled in the official builds. david continues to create svg enabled nightlies and answer build related questions as he has done for some time. finally,...
Space Manager Detailed Design - Archive of obsolete content
ft, nscoord atop, nscoord aright, nscoord abottom, nsiframe*); bandrect(nscoord aleft, nscoord atop, nscoord aright, nscoord abottom, nsvoidarray*); ~bandrect(); // list operations bandrect* next() const {return (bandrect*)pr_next_link(this);} bandrect* prev() const {return (bandrect*)pr_prev_link(this);} void insertbefore(bandrect* abandrect) {pr_insert_before(abandrect, this);} void insertafter(bandrect* abandrect) {pr_insert_after(abandrect, this);} void remove() {pr_remove_link(this);} // split the band rect into two vertically, with this band rect becoming // the top part, and a new band rect being allocated and returned for the // bottom part // // does not insert the ne...
.../ +-----+ // | r | // +-----+ // first, check for the easiest case, where there are no existing bandrects, or the band rect passed in is below the bottommost rect. in this case,just append the band rect and return. starting at the head of the list of bandrects, check for intersection with the rect passed in: case #1: the rect is totally above the current band rect, so insert a new band rect before the current bandrect cases #2 and #7: the rect is partially above the band rect, so it is divided into two bandrects, one entirely above the band, and one containing the remainder of the rect. insert the part that is totally above the bandrect before the current bandrect, as in case #1 above, and adjust the other band rect to exclude the part already added. case #5: the rect is totally below th...
Actionscript Acceptance Tests - Archive of obsolete content
.abcs: if you desire to run a test with multiple .abc files (e.g: avmshell a.abc b.abc testname.abc) there is a special avm_args directive called multiabc that is specified surrounded by two pipe (|) symbols: |multiabc| $dir/testname_support/a.abc $dir/testname_support/b.abc the extra abc files will usually be placed in a _support dir (see additional files below). 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 that will apply to the entire directory. te...
...ed line by line to the .out file and any difference is considered a failure. may be used in conjunction with a .exitcode file. testname.abc_ for special cases where the .as source is not available (e.g. fuzzed files) it is possible to check in a .abc_ which will let the test harness run compiled files without source. the underscore is necessary otherwise the buildbot system will delete the .abc before starting up a testrun (not an issue when running locally, but makes it easy to differentiate between binary-only abc files and generated abcs. support directories in some cases a test may require additional files to successfully run. there are two kinds of support directories available. files to be included when compiling the test: if a test requires additional .as files to be included when comp...
Treehydra Manual - Archive of obsolete content
a options. to make things easier, we will first present recipes for accessing specific gcc intermediate representations. treehydra provides the following callbacks to analysis scripts: process_tree_decl, process_tree, process_tree_type, and process_cp_pre_genericize. fixme document all these callbacks. c++ asts c++ asts are provided via the process_cp_pre_genericize callback. ...
...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. ...
Anonymous Content - Archive of obsolete content
th the bound element takes focus, then the blur and focus events are both stopped. as far as the bound element is concerned, it retains focus throughout the two events. anonymous content can receive focus when the user tabs through the document. the same rules apply. if the anonymous content is focusable, it can be tabbed into, but if the bound element is not focusable, the event will be stopped before it reaches the bound element. in html4 the tabindex attribute can be used to specify the tab order for focusable elements. this attribute can be specified on anonymous content. each scope has a unique tab order. the tabindex values used in one scope are ignored by other scopes. as an example, consider the html file upload control. it is a focusable element that in turn is made up of two focusab...
...targeted to be a focus event on the file control itself. focus events should also be stopped if the bound element is already focused. for example, if the user has already focused the textfield within an html file upload control, then the file upload control is now also focused. if the user then focuses the button inside the file upload control, the focus event generated for the button is stopped before it reaches the file control, since the file control is already focused. because content in multiple scopes can be focused, the css :focus pseudo-element is hierarchical. style rules can be written with the assumption that they will match (in the above example) both the file control and the element focused inside the file control. in other words, an arbitrary chain of elements can be in the :focu...
Binding Attachment and Detachment - Archive of obsolete content
ethods and properties with getters/setters are no longer accessible from the binding, although properties with raw values remain. any specified event handlers are unhooked from their respective targets. a binding can specify a <destructor> block within <implementation> section that executes prior to the binding detachment. using a <destructor> block, a binding can perform any necessary cleanup before it is torn down. bindings in an inheritance chain are always detached from the most derived binding to the base. therefore the <destructor> block of the derived binding will execute, and then the base binding's block will execute. when bindings attached through style are detached because of a style change, they have no effect on any other bindings attached using the dom. those bindings will sta...
...talled via the original call to element.style.mozbinding = "url(...)". the rule for detachment can be summarized as follows. whenever a binding is detached, all bindings that it explicitly inherits from are also detached. binding documents whenever a binding is attached to an element in another document, the binding document is only fetched if no binding from the binding document has been used before in the bound document. a given bound document has a unique copy of each separate binding document that it uses. all bindings from the same binding document url that are used in a bound document will share the same binding document. therefore if all the bindings in a chain come from binding documents that have already been loaded by the bound document, then the attachment of a binding (either thr...
Event Handlers - Archive of obsolete content
d to and if that event matches all of the criteria specified by the handler. 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. in both cases the javascript body is compiled just before execution; code that does not depend on the context of the 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 el...
...s 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 flowing to its base binding handlers. mouse and key handlers have certain additional properties that are supported by xbl. additional attributes can be used to impose a filter on the event handler. when a filter is imposed, additional conditions must be met before the event handler will fire. for both mouse and key events, modifier keys can be specified using the modifiers attribute. this attribute is a comma-separated list of modifier keys that must be down at the time the key or mouse event occurs in order for the handler to execute. examples of common keys in the list are shift and control. for more details, see the xbl element reference for <handler>...
execute - Archive of obsolete content
parameters the execute method has the following parameters: xpisourcepath the pathname of the file to extract and execute. (note that this path points into the xpi itself.) args a parameter string that is passed to the executable. (ignored on mac os). see note below. blocking a boolean value that specifies whether the installation should wait for the execution of the file to finish before it resumes. default is false. see note below. the blocking parameter is not available as part of this method in versions of netscape before 6.1/mozilla 0.9.3. returns an integer error code. for a list of possible values, see return codes. description the execute method extracts the named file from the xpi file to a temporary file name. your code must call the performinstall method to actual...
...le (such as a browser) after it has been installed, and is typically placed at the end of an install script and outside of the main install block. the install object's execute method, on the other hand, deletes the executable from its temporary location once it has finished. the optional blocking argument, when set to true, specifies that the installation should wait for this executable to finish before processing the next queued install command. if you do not set this flag and launch an executable that is not a part of the installation, you will raise an error when you restart the browser. passing arguments to the executable the args parameter, when present, passes a string to the executable as command-line parameters. the following line, for example, passes the "-c" command-line parameter to ...
rel - Archive of obsolete content
Archive › Mozilla › XUL › Attribute › rel
« xul reference home rel type: one of the values below the type of comparison to perform. equals the subject and value must match exactly. ...
... « xul reference home rel type: one of the values below the type of comparison to perform. equals the subject and value must match exactly. ...
substate - Archive of obsolete content
after the element immediately after the splitter is collapsed. ...
... after the element immediately after the splitter is collapsed. ...
Building accessible custom components in XUL - Archive of obsolete content
nrelated text labels. if we inspect this with the msaa inspect32 tool, we see that each cell is exposed as role="text". <caption>it looks like a cell, but it's not</caption> assistive technologies also have no idea that our row headers and column headers are really headers. again, they are exposed as role="text". <caption>it looks like a column header, but it's not</caption> so, before we do anything else, we need to tell assistive technologies that all of these unrelated elements are actually related. this is where dhtml accessibility comes in. further reading grid element reference description element reference label element reference grid tutorial label tutorial adding roles with dhtml accessibility download stage-2.zip install stage-2.xpi using the new dhtml accessibili...
... "cancel" the edit by simply recreating the original label and restoring its previous value. finally, if the user hits tab while editing, we treat this as acceptance and recreate the label with the new value, then let firefox manage changing focus to the spreadsheet's next sibling. ...
ContextMenus - Archive of obsolete content
any of these situations; the 'contextmenu' event is fired in any case. <hbox id="container" align="center" oncontextmenu="..."> <label value="name:"/> <textbox id="name"/> </hbox> in this example, an attempt to open a context menu anywhere inside the hbox will call the event listener attached using the oncontextmenu attribute. as textboxes have a context menu built in, the event will fire before an attempt to open the context menu. however, the event will also fire when the label is right-clicked for instance, so the event handler should check to make sure that the target of the contextmenu event is what is desired. to cancel a context menu event, you can use the preventdefault method of the event object. function checkcontextmenu(event) { if (event.target.localname == "textbox") ...
...cause the context attribute is set to '_child'. note that this special value must begin with an underscore to distinguish it from an id of 'child'. the menupopup does not have to be the last child of the element as in this example, but usually this will be a convenient place to put it. hiding and showing menu items based on context when the context menu is opened, a popupshowing event will fire before the popup is displayed. this may be used to adjust the items displayed on the menu. typically, this will vary based on what the context is. for example, right clicking on an image might display items pertaining to images, whereas clicking on a link would display items pertaining to links. in many cases, it may be easier to use a single context menu containing every possible item, and show and hi...
Multiple Rules - Archive of obsolete content
ere element may be used. beside the equals operator, there are several other operators that may be used. ...
...de the equals operator, there are several other operators that may be used. ...
RDF Modifications - Archive of obsolete content
t creates a fresh datasource with the new data. actually, the parser does something smarter. when reloading a datasource, it keeps the existing rdf triples intact, and only modifies the datasource based on what has changed. when parsing, any triples that already exist are not added again. if a triple does not exist yet, it will be added. any triples that don't exist in the new data but were there before are removed. this means that the observer will be called only for the triples that differ between the new and old version of the data. if the reloaded datasource hasn't changed, the builder won't receive any notifications. this saves a lot of extra work. the rdf observer also has two methods onbeginupdatebatch and onendupdatebatch. these are called when performing a lot of operations on a datasou...
...ined in a parent container, there would be no match and the builder could stop processing the new triple. for instance, we might have added a description for a new photo, but haven't added the photo to the container resource. once we do add it to the container with another rdf assertion, the process described above is applied again and this time it may match. there are still two more things to do before a result is accepted as a new match. first, once the builder reaches the content statement, it checks what the container or reference variable is, in this case ?start, as specified by the uri attribute. the calculated value for the potential new match is 'http://www.xulplanet.com/rdf/myphotos'. the builder looks to see if this resource is being used as the stating point in the template. as it hap...
textbox (Toolkit autocomplete) - Archive of obsolete content
resses the "tab" key. elements with a higher tabindex are later in the tab sequence. tabscrolling new in thunderbird 3requires seamonkey 2.0 type: boolean if true, the user may cycle through the results list by pressing the tab key. if false, the default, the tab key moves the focus to the next element. timeout type: integer for autocomplete textboxes, the number of milliseconds before the textbox starts searching for completions. the default is 50 milliseconds. for search textboxes, the number of milliseconds before the timer fires a command event. the default is 500 milliseconds. for timed textboxes, the number of milliseconds before the timer fires a command event. there is no default. the timer starts after the user types a character. if the user types another character, th...
...node(), comparedocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), removeattributenode(), removeattributens(), removechild(), removeeventlistener(), replacechild(), setattribute(), setattributenode(), setattributenodens(), setattributens(), setuserdata getsearchat( index ) return type: str...
Textbox (XPFE autocomplete) - Archive of obsolete content
ext element.as of gecko 1.9.1, this attribute is now always specified in lower case. tabscrolling new in thunderbird 3requires seamonkey 2.0 type: boolean if true, the user may cycle through the results list by pressing the tab key. if false, the default, the tab key moves the focus to the next element. timeout type: integer for autocomplete textboxes, the number of milliseconds before the textbox starts searching for completions. the default is 50 milliseconds. for search textboxes, the number of milliseconds before the timer fires a command event. the default is 500 milliseconds. for timed textboxes, the number of milliseconds before the timer fires a command event. there is no default. the timer starts after the user types a character. if the user types another character, th...
...node(), comparedocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), removeattributenode(), removeattributens(), removechild(), removeeventlistener(), replacechild(), setattribute(), setattributenode(), setattributenodens(), setattributens(), setuserdata addsession( session ) obsolete since g...
Custom toolbar button - Archive of obsolete content
e to specify custom-button-2. duplicate the last section. in the id and oncommand attributes, change 1 to 2. change the label and tooltiptext attributes to whatever you want. do not change the class attribute. now edit button.css. duplicate the first three lines, changing the new lines to specify button-2. edit button.js and add javascript code for the new button. be sure to add the extra code before the curly brace on the last line of the file. for example, you could add this code for testing: 2: function () { alert("just testing again") }, create an image for the new button, naming the file button-2.png. the images supplied here are 40 pixels wide and 48 pixels high, with a 256-colour palette and a transparent background, in png format. some other formats will also work. here are so...
... as you need. distributing your button to other users if you want to distribute your button or buttons to other users, you must make some changes to avoid conflicts when they install your extension. create a new extension id, in the form: something@domain-name it must contain an at-sign (@), 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 and underscore. if you do not own a domain name, you can make up something else. if you want to make it clear that your made-up name is not a real domain, add .invalid to the end. use your new extension id to rename the directory, and specify the same id in your install.rdf file. in your install.rdf file,...
Toolbar customization events - Archive of obsolete content
when toolbars are customized, events are sent to their parent window. you can use window.addeventlistener() to listen for these events in order to keep abreast of changes to toolbars. none of these events contain any data; if you need details, you'll need to look at the toolbar. beforecustomization this event is delivered when the user starts the toolbar customization process; for example, by right-clicking on a toolbar and choosing "customize". customizationchange this event is delivered when the user makes a change to a toolbar while editing the toolbars, either by dragging an item to the toolbar or by dragging an item out of it. aftercustomization this event is delivered when the user closes the toolbar customization panel. in all cases, the event.target is the tool...
...m to the toolbar or by dragging an item out of it. aftercustomization this event is delivered when the user closes the toolbar customization panel. in all cases, the event.target is the toolbox being customized. you can look at the contents of that element and its children to determine what changes were made. example in this example, we watch for toolbar changes. ...
Adding Style Sheets - Archive of obsolete content
lso needs to be created. create a file findfile.css in the same directory as the xul file. (it would normally be put into a separate skin). in this file, we'll add the style declarations, as shown below: #find-text { min-width: 15em; } #progmeter { margin: 4px; } .springspace { width: 10px; } .titlespace { height: 10px; } notice how these styles are equivalent to the styles we had before. however, it is much easier for someone to change the look of the find files dialog now because they could add or modify the style declarations by either modifying the file or by changing the skin. if the user changes 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 b...
... 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.css. all elements can be styled using css. you can use selectors to select the element that you wish to have styled. (the selector is the part before the curly brace in a style rule). the following list summarizes some of the selectors available: button matches all button tags. #special-button matches the element with an id of special-button. .bigbuttons matches all elements with a class of bigbuttons. button.bigbuttons matches all button elements with a class of bigbuttons. t...
Commands - Archive of obsolete content
s to happen for the onevent method, so no code is added for this method. override default controller we attach this controller to the listbox by calling the appendcontroller method of the listbox's controllers. nsicontrollers has a number of methods that may be used to manipulate the controllers. for instance, there is also an insertcontrollerat method which inserts a controller into an element before other ones. this might be useful to override commands. for example, the following example will disable pasting into a textbox. var tboxcontroller = { supportscommand : function(cmd){ return (cmd == "cmd_paste"); }, iscommandenabled : function(cmd){ return false; }, docommand : function(cmd){ }, onevent : function(evt){ } }; document.getelementbyid("tbox").controllers.insertcontrollerat(...
...ple will disable pasting into a textbox. var tboxcontroller = { supportscommand : function(cmd){ return (cmd == "cmd_paste"); }, iscommandenabled : function(cmd){ return false; }, docommand : function(cmd){ }, onevent : function(evt){ } }; document.getelementbyid("tbox").controllers.insertcontrollerat(0,tboxcontroller); in this example, we insert the controller at index 0, which means before any others. the new controller supports the 'cmd_paste' command and always indicates that the command is disabled. the default textbox controller never gets called because the command dispatcher found the controller above to handle the command first. next, we'll find out how to update commands. « previousnext » ...
Manifest Files - Archive of obsolete content
ten. for standalone applications, they can be packaged up using xulrunner. this allows a separate executable file, and the application may be distributed independently of a browser. for more information about creating extensions, see extensions. for more information about xulrunner, see xulrunner. older applications if you are creating applications for older versions of mozilla software, that is, before firefox 1.5 or mozilla 1.8, the process is a bit more involved. the following describes how to set up a package for earlier versions. this section may be skipped if you are writing new extensions or xul applications. note: this older process does also apply to the new seamonkey 1.0 though. the codebase there has not yet adopted the "manifest" format. <?xml version="1.0"?> <rdf:rdf xmlns:rdf="h...
...rome:extension' field is true, the application is a mozilla firefox extension and it will show up in the extensions window of the browser. if false, it will not appear. save the contents.rdf and make sure it is in the directory you created in step 1. open the file <mozilla-directory>/chrome/installed-chrome.txt, where <mozilla-directory> is the directory where mozilla is installed. exit mozilla before you do this. next, you are going to register the new application with mozilla so it will know where to find it. add a line at the end of installed-chrome.txt pointing to the new directory you created in step 1. change the highlighted text to the file url below of the directory. make sure that it url ends with a slash and that you press enter at the end of the line. if you aren't sure what the ur...
Modifying a XUL Interface - Archive of obsolete content
ments, this generally means that a xul element will be created. for an html document, an html element will be created, so it will have the features and functions of an html element instead. the createelementns() function may be used to create elements in a different namespace. the appendchild() function is used to add an element as a child of another element. three related functions are the insertbefore(), replacechild() and removechild functions. the syntax of these functions is as follows: parent.appendchild(child); parent.insertbefore(child, referencechild); parent.replacechild(newchild, oldchild); parent.removechild(child); it should be fairly straightforward from the function names what these functions do. the insertbefore() function inserts a new child node before an existing one. this...
...ing node so that you can add it somewhere else. the original node will stay where it is. it takes one boolean argument which indicates whether to copy all of the node's children or not. if false, only the node is copied, such that the copy won't have any children. if true, all of the children are copied as well. this is done recursively, so for large tree structures make sure that this is desired before passing true to the clonenode() function. here is an example: example 2 : source view <hbox height="400"> <button label="copy" oncommand="this.parentnode.appendchild(this.nextsibling.clonenode(true));"/> <vbox> <button label="first"/> <button label="second"/> </vbox> </hbox> when the copy button is pressed.. we retrieve the nextsibling of the button, which will be the...
Styling a Tree - Archive of obsolete content
d this property is set for odd numbered rows. this property, along with the even property allow you to set, for example, alternating colors for each row. dragsession this property is set if something is currently being dragged. dropon if a drag is occuring over the tree, this property is set for the row currently being dragged over, as long as the mouse pointer is hovering over the row. dropbefore this property is set if the mouse pointer is hovering before the row currently being dragged over. dropafter this property is set if the mouse pointer is hovering after the row currently being dragged over. progressnormal this property is set for progress meter cells. progressundetermined this property is set for undeterminate progress meter cells. progressnone this property is set for n...
...ing the xpcom interface nsiatomservice and add them to the array using the appendelement() function. here, we create an atom 'makeitblue'. you can call appendelement() again to add additional properties. from gecko 22 your function should return a string containing the property. getcellproperties: function(row,col){ if ((row %4) == 0){ return "makeitblue"; } } to support gecko versions before and after this change use. getcellproperties: function(row,col,props){ if ((row %4) == 0){ if (props) { var aserv=components.classes["@mozilla.org/atom-service;1"]. getservice(components.interfaces.nsiatomservice); props.appendelement(aserv.getatom("makeitblue")); } else { return "makeitblue"; } } } this function would be defined as part of a v...
Tree Box Objects - Archive of obsolete content
t too hard to calculate manually anyway since the tree box object also provides a getpagelength() function which returns the number of rows in a page. in the scrolling example above, getpagelength() would return four. note that in firefox 1.0 and mozilla 1.7 and earlier, the getpagelength() function is called getpagecount() instead. the name was changed to getpagelength() since it was confusing before since it doesn't return the number of pages, but the size of each page. you could determine the number of pages by dividing the total number of rows by the page length. the ensurerowisvisible() function will scroll to a row just as scrolltorow() does, but does not scroll if the row is already visible. cell coordinates some of the most interesting functions of the tree box object are several f...
...bel id="column"/> <label value="child type:"/> <label id="part"/> the getcellat() function takes five arguments, the coordinates to look up and three out parameters. an out parameter is used since the function needs to return more that one value. you will see a number of interfaces that use out parameters in the xulplanet object reference (fixme: deadlink). these are indicated by the word 'out' before the argument. for these, you will need to supply an empty object and the function will fill in the 'value' property with the necessary value. the three out parameters will be filled in with the row, the column and a child type. the row is the index of 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 wi...
Tree View Details - Archive of obsolete content
ermine the hierarchical structure of the rows. in addition to the getlevel method, there is a hasnextsibling function which, given a row, should return true if there is another row afterwards at the same level. this function is used, specifically, to draw the nesting lines along the side of the tree. the getparentindex method is expected to return the parent row of a given row, that is, the row 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...
... and removed from this array when items are opened or closed. essentially, when a parent row is opened, the children will be taken from the childdata map and inserted into the visibledata array. for example, if the liquids row was opened, the corresponding array from childdata, which in this case contains only the single mercury child, will be inserted into the visibledata array after liquids but before gases. this will increase the array size by one. the two booleans in each row in the visibledata structure indicate whether a row is a container and whether it is open respectively. obviously, the new inserted child items will have both values set to false. implement the tree view interface next, we need to implement the tree view interface. first, the simple functions: { treebox: null, se...
Using Spacers - Archive of obsolete content
s inside it. each time we add something, the window gets bigger. xul uses a layout system called the 'box model'. we'll talk more about this in the next section but it essentially allows you to divide a window into a series of boxes that hold elements. the boxes will be positioned and resized based on specifications that you can define. for now, just know that the window element is a type of box. before we get into detail about boxes, we'll introduce another xul element that is useful for layout, the spacer. a spacer is very simple and only requires one attribute, which will be explained in a moment. the simplest spacer looks like the following: <spacer flex="1"/> a spacer is used to place blank space into a window. its most useful ability is that it can grow or shrink as the user resizes the w...
...ted. none of them have been moved or resized even though the window has more room in it. let's see what happens when a spacer is added between the text box and the find button. by adding a spacer and resizing the window, you can see that the spacer has expanded to fill the space. the buttons have been pushed over. our find file example the code to add a spacer is shown below. insert it just before the find button. <spacer flex="1"/> <button id="find-button" label="find"/> more about flexibility xul lays out elements on a window by calculating suitable widths and heights for the elements and then adding space where they are flexible. unless you specify information about the width and height of an element, the default size of an element is determined by its contents. you'll notice that ...
XUL accessibility guidelines - Archive of obsolete content
style to "overflow: auto" or "overflow: scroll". this flexibility should be used carefully. maintaining focus the user should typically control where the current focus is located. avoid changing the focus automatically. however, disabling, hiding, or destroying the focus element (or any ancestor of the focus element) can cause a loss of focus. to prevent this, move the focus to the next element before disabling, hiding, or destroying the focus element. the following example shows a javascript function that can be called before destroying an element to check for focus and move it if necessary. function movefocus(element) { if(element == document.commanddispatcher.focusedelement) { document.commanddispatcher.advancefocus(); return true; } return false; } ch...
... animation animation, movement, and audio can all be distracting to some users with attention disorders. provide a mechanism for turning media and movement on and off. flickering or flashing is not only just annoying to everyone, but at a rate more than 3 cycles per second it can cause a seizure in users with photosensitive epilepsy. if flickering or flashing is necessary then warn the user before it is displayed. testing media ensure that media alternatives are available in an accessible format. other issues custom widgets avoid re-creating functionality that already exists. ensure that custom components are built with accessibility in mind. use css system colors to ensure that new widgets interact well with other widgets and with user-defined colors and themes. learn more ...
action - Archive of obsolete content
variable appears multiple times, it will have the same value in each place. for more information, see actions. ...
...aredocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), removeattributenode(), removeattributens(), removechild(), removeeventlistener(), replacechild(), setattribute(), setattributenode(), setattributenodens(), setattributens(), setuserdata ...
arrowscrollbox - Archive of obsolete content
gold"/> <button label="turquoise"/> <button label="peach"/> <button label="maroon"/> <button label="black"/> </arrowscrollbox> attributes inherited from xul element align, allowevents, allownegativeassertions, class, coalesceduplicatearcs, collapsed, container, containment, context, contextmenu, datasources, dir, empty, equalsize, flags, flex, height, hidden, id, insertafter, insertbefore, left, maxheight, maxwidth, menu, minheight, minwidth, mousethrough, observes, ordinal, orient, pack, persist, popup, position, preference-editable, querytype, ref, removeelement, sortdirection, sortresource, sortresource2, statustext, style, template, tooltip, tooltiptext, top, uri, wait-cursor, width clicktoscroll type: boolean clicktoscroll, if true, the arrows must be clicked to s...
...aredocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), removeattributenode(), removeattributens(), removechild(), removeeventlistener(), replacechild(), setattribute(), setattributenode(), setattributenodens(), setattributens(), setuserdata ...
assign - Archive of obsolete content
ing 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". ...
...aredocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), removeattributenode(), removeattributens(), removechild(), removeeventlistener(), replacechild(), setattribute(), setattributenode(), setattributenodens(), setattributens(), setuserdata ...
bbox - Archive of obsolete content
Archive › Mozilla › XUL › bbox
hat is baseline aligned. it is equivalent to using an hbox element with an align attribute set to baseline. ...
...aredocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), removeattributenode(), removeattributens(), removechild(), removeeventlistener(), replacechild(), setattribute(), setattributenode(), setattributenodens(), setattributens(), setuserdata ...
binding - Archive of obsolete content
name can then be used within the action of a rule. properties object, predicate, subject examples fixme: (example needed) attributes inherited from xul element align, allowevents, allownegativeassertions, class, coalesceduplicatearcs, collapsed, container, containment, context, contextmenu, datasources, dir, empty, equalsize, flags, flex, height, hidden, id, insertafter, insertbefore, left, maxheight, maxwidth, menu, minheight, minwidth, mousethrough, observes, ordinal, orient, pack, persist, popup, position, preference-editable, querytype, ref, removeelement, sortdirection, sortresource, sortresource2, statustext, style, template, tooltip, tooltiptext, top, uri, wait-cursor, width properties object type: string the object of the element. it can be a variable refer...
...aredocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), removeattributenode(), removeattributens(), removechild(), removeeventlistener(), replacechild(), setattribute(), setattributenode(), setattributenodens(), setattributens(), setuserdata related tbd ...
bindings - Archive of obsolete content
ments may be placed directly inside the rule element. more information is available in the template guide. examples (example needed) attributes inherited from xul element align, allowevents, allownegativeassertions, class, coalesceduplicatearcs, collapsed, container, containment, context, contextmenu, datasources, dir, empty, equalsize, flags, flex, height, hidden, id, insertafter, insertbefore, left, maxheight, maxwidth, menu, minheight, minwidth, mousethrough, observes, ordinal, orient, pack, persist, popup, position, preference-editable, querytype, ref, removeelement, sortdirection, sortresource, sortresource2, statustext, style, template, tooltip, tooltiptext, top, uri, wait-cursor, width object type: string the object of the element. it can be a variable reference, an r...
...aredocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), removeattributenode(), removeattributens(), removechild(), removeeventlistener(), replacechild(), setattribute(), setattributenode(), setattributenodens(), setattributens(), setuserdata related tbd ...
box - Archive of obsolete content
Archive › Mozilla › XUL › box
"/> <label value="two"/> </box> <box orient="horizontal"> <label value="three"/> <label value="four"/> </box> </box> attributes inherited from xul element align, allowevents, allownegativeassertions, class, coalesceduplicatearcs, collapsed, container, containment, context, contextmenu, datasources, dir, empty, equalsize, flags, flex, height, hidden, id, insertafter, insertbefore, left, maxheight, maxwidth, menu, minheight, minwidth, mousethrough, observes, ordinal, orient, pack, persist, popup, position, preference-editable, querytype, ref, removeelement, sortdirection, sortresource, sortresource2, statustext, style, template, tooltip, tooltiptext, top, uri, wait-cursor, width properties inherited properties align, , allowevents, , boxobject, builder, , , , c...
...aredocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), removeattributenode(), removeattributens(), removechild(), removeeventlistener(), replacechild(), setattribute(), setattributenode(), setattributenodens(), setattributens(), setuserdata related elements vbox, hbox ...
broadcaster - Archive of obsolete content
e a command element instead. more information is available in the broadcasters and observers xul tutorial. ...
...aredocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), removeattributenode(), removeattributens(), removechild(), removeeventlistener(), replacechild(), setattribute(), setattributenode(), setattributenodens(), setattributens(), setuserdata ...
broadcasterset - Archive of obsolete content
e broadcasterset and its descendants are not displayed. more information is available in the xul tutorial. ...
...aredocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), removeattributenode(), removeattributens(), removechild(), removeeventlistener(), replacechild(), setattribute(), setattributenode(), setattributenodens(), setattributens(), setuserdata ...
browser - Archive of obsolete content
ontent type. this boundary has a number of special effects, such as making window.top == window (unless the browser is added to a chrome document), and preventing documents from inheriting the principal of the parent document. the type attribute on all frames in content documents is ignored; subdocuments of content documents are always content documents. warning: the type attribute must be set before the element is inserted into the document. content a browser for content. the content that is loaded inside the browser is not allowed to access the chrome above it. content-primary the primary browser for content. the content that is loaded inside the browser is not allowed to access the chrome above it. for instance, in a web browser, this would be the element that displays the we...
...node(), comparedocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), removeattributenode(), removeattributens(), removechild(), removeeventlistener(), replacechild(), setattribute(), setattributenode(), setattributenodens(), setattributens(), setuserdata addprogresslistener( listener )...
column - Archive of obsolete content
d not place elements directly inside the column. more information is available in the xul tutorial. example see grid for an example. ...
...aredocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), removeattributenode(), removeattributens(), removechild(), removeeventlistener(), replacechild(), setattribute(), setattributenode(), setattributenodens(), setattributens(), setuserdata related elements grid, columns, rows...
columns - Archive of obsolete content
g positions between the columns. more information about columns is available in the xul tutorial. example see grid for an example. ...
...aredocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), removeattributenode(), removeattributens(), removechild(), removeeventlistener(), replacechild(), setattribute(), setattributenode(), setattributenodens(), setattributens(), setuserdata related elements grid, column, rows,...
conditions - Archive of obsolete content
2/mozilla 1.8 and earlier instead of the query element. more information is available in the xul tutorial. ...
...aredocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), removeattributenode(), removeattributens(), removechild(), removeeventlistener(), replacechild(), setattribute(), setattributenode(), setattributenodens(), setattributens(), setuserdata ...
content - Archive of obsolete content
lugar. para más información, se encuentra disponible el tutorial xul. propiedades tag, uri ejemplos (no son necesarios) atributos inherited from xul element align, allowevents, allownegativeassertions, class, coalesceduplicatearcs, collapsed, container, containment, context, contextmenu, datasources, dir, empty, equalsize, flags, flex, height, hidden, id, insertafter, insertbefore, left, maxheight, maxwidth, menu, minheight, minwidth, mousethrough, observes, ordinal, orient, pack, persist, popup, position, preference-editable, querytype, ref, removeelement, sortdirection, sortresource, sortresource2, statustext, style, template, tooltip, tooltiptext, top, uri, wait-cursor, width propiedades tag type: tag name this may be set to a tag name. if set, the condition...
...aredocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), removeattributenode(), removeattributens(), removechild(), removeeventlistener(), replacechild(), setattribute(), setattributenode(), setattributenodens(), setattributens(), setuserdata relacionados tbd ...
deck - Archive of obsolete content
Archive › Mozilla › XUL › deck
x> </deck> attributes selectedindex type: integer gets and sets the index of the currently selected panel. the first item is at index 0. ...
...aredocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), removeattributenode(), removeattributens(), removechild(), removeeventlistener(), replacechild(), setattribute(), setattributenode(), setattributenodens(), setattributens(), setuserdata related stack ...
dropmarker - Archive of obsolete content
he popup type of datepicker use a dropmarker, that when pressed, will reveal a popup menu. ...
...aredocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), removeattributenode(), removeattributens(), removechild(), removeeventlistener(), replacechild(), setattribute(), setattributenode(), setattributenodens(), setattributens(), setuserdata ...
grid - Archive of obsolete content
Archive › Mozilla › XUL › grid
e"/> <menuitem label="support"/> </menupopup> </menulist> </row> </rows> </grid> </groupbox> attributes inherited from xul element align, allowevents, allownegativeassertions, class, coalesceduplicatearcs, collapsed, container, containment, context, contextmenu, datasources, dir, empty, equalsize, flags, flex, height, hidden, id, insertafter, insertbefore, left, maxheight, maxwidth, menu, minheight, minwidth, mousethrough, observes, ordinal, orient, pack, persist, popup, position, preference-editable, querytype, ref, removeelement, sortdirection, sortresource, sortresource2, statustext, style, template, tooltip, tooltiptext, top, uri, wait-cursor, width properties inherited properties align, , allowevents, , boxobject, builder, , , , c...
...aredocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), removeattributenode(), removeattributens(), removechild(), removeeventlistener(), replacechild(), setattribute(), setattributenode(), setattributenodens(), setattributens(), setuserdata related elements columns, column, ro...
grippy - Archive of obsolete content
be used to collapse a sibling element of the splitter. more information is available in the xul tutorial. ...
...aredocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), removeattributenode(), removeattributens(), removechild(), removeeventlistener(), replacechild(), setattribute(), setattributenode(), setattributenodens(), setattributens(), setuserdata ...
groupbox - Archive of obsolete content
radiogroup> <radio label="black and white"/> <radio label="colour"/> </radiogroup> <checkbox label="enabled"/> </groupbox> attributes inherited from xul element align, allowevents, allownegativeassertions, class, coalesceduplicatearcs, collapsed, container, containment, context, contextmenu, datasources, dir, empty, equalsize, flags, flex, height, hidden, id, insertafter, insertbefore, left, maxheight, maxwidth, menu, minheight, minwidth, mousethrough, observes, ordinal, orient, pack, persist, popup, position, preference-editable, querytype, ref, removeelement, sortdirection, sortresource, sortresource2, statustext, style, template, tooltip, tooltiptext, top, uri, wait-cursor, width properties accessibletype type: integer a value indicating the ty...
...aredocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), removeattributenode(), removeattributens(), removechild(), removeeventlistener(), replacechild(), setattribute(), setattributenode(), setattributenodens(), setattributens(), setuserdata related interfaces nsiaccessibleprov...
hbox - Archive of obsolete content
Archive › Mozilla › XUL › hbox
l. ...
...aredocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), removeattributenode(), removeattributens(), removechild(), removeeventlistener(), replacechild(), setattribute(), setattributenode(), setattributenodens(), setattributens(), setuserdata related elements box, vbox ...
keyset - Archive of obsolete content
ailable in the xul tutorial. attributes disabled examples <keyset> <key id="sample-key" modifiers="shift" key="r"/> </keyset> attributes inherited from xul element align, allowevents, allownegativeassertions, class, coalesceduplicatearcs, collapsed, container, containment, context, contextmenu, datasources, dir, empty, equalsize, flags, flex, height, hidden, id, insertafter, insertbefore, left, maxheight, maxwidth, menu, minheight, minwidth, mousethrough, observes, ordinal, orient, pack, persist, popup, position, preference-editable, querytype, ref, removeelement, sortdirection, sortresource, sortresource2, statustext, style, template, tooltip, tooltiptext, top, uri, wait-cursor, width disabled type: boolean indicates whether the element is disabled or not. if this at...
...aredocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), removeattributenode(), removeattributens(), removechild(), removeeventlistener(), replacechild(), setattribute(), setattributenode(), setattributenodens(), setattributens(), setuserdata ...
listbox - Archive of obsolete content
node(), comparedocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), removeattributenode(), removeattributens(), removechild(), removeeventlistener(), replacechild(), setattribute(), setattributenode(), setattributenodens(), setattributens(), setuserdata additemtoselection( item ) return ty...
...given item, without deselecting any other items that are already selected. appenditem( label, value ) return type: element creates a new item and adds it to the end of the existing list of items. you may optionally set a value. the function returns the newly created element. clearselection() return type: no return value deselects all of the items. a select event is sent before the items are deselected. ensureelementisvisible( element ) return type: no return value if the specified element is not currently visible to the user, the displayed items are scrolled so that it is. if the item is already visible, no scrolling occurs. ensureindexisvisible( index ) return type: no return value if the item at the specified index is not currently visible to the user the dis...
listcol - Archive of obsolete content
cell label="rogers"/> </listitem> <listitem> <listcell label="john"/> <listcell label="painter"/> </listitem> </listbox> attributes inherited from xul element align, allowevents, allownegativeassertions, class, coalesceduplicatearcs, collapsed, container, containment, context, contextmenu, datasources, dir, empty, equalsize, flags, flex, height, hidden, id, insertafter, insertbefore, left, maxheight, maxwidth, menu, minheight, minwidth, mousethrough, observes, ordinal, orient, pack, persist, popup, position, preference-editable, querytype, ref, removeelement, sortdirection, sortresource, sortresource2, statustext, style, template, tooltip, tooltiptext, top, uri, wait-cursor, width properties inherited properties align, , allowevents, , boxobject, builder, , , , c...
...aredocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), removeattributenode(), removeattributens(), removechild(), removeeventlistener(), replacechild(), setattribute(), setattributenode(), setattributenodens(), setattributens(), setuserdata related elements listbox, listcell, ...
listcols - Archive of obsolete content
cell label="rogers"/> </listitem> <listitem> <listcell label="john"/> <listcell label="painter"/> </listitem> </listbox> attributes inherited from xul element align, allowevents, allownegativeassertions, class, coalesceduplicatearcs, collapsed, container, containment, context, contextmenu, datasources, dir, empty, equalsize, flags, flex, height, hidden, id, insertafter, insertbefore, left, maxheight, maxwidth, menu, minheight, minwidth, mousethrough, observes, ordinal, orient, pack, persist, popup, position, preference-editable, querytype, ref, removeelement, sortdirection, sortresource, sortresource2, statustext, style, template, tooltip, tooltiptext, top, uri, wait-cursor, width properties inherited properties align, , allowevents, , boxobject, builder, , , , c...
...aredocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), removeattributenode(), removeattributens(), removechild(), removeeventlistener(), replacechild(), setattribute(), setattributenode(), setattributenodens(), setattributens(), setuserdata related elements listbox, listcell, ...
listhead - Archive of obsolete content
sabled property which, except for menus and menuitems, is normally preferred to use of the attribute, as it may need to update additional state. ...
...aredocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), removeattributenode(), removeattributens(), removechild(), removeeventlistener(), replacechild(), setattribute(), setattributenode(), setattributenodens(), setattributens(), setuserdata related elements listbox, listcell, ...
listheader - Archive of obsolete content
ears. for an editable menuitem element the value of this attribute is copied to the menulist.value property upon user selection of the menuitem. ...
...aredocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), removeattributenode(), removeattributens(), removechild(), removeeventlistener(), replacechild(), setattribute(), setattributenode(), setattributenodens(), setattributens(), setuserdata related elements listbox, listcell, ...
member - Archive of obsolete content
tes may use variables. more information is available in the xul tutorial. ...
...aredocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), removeattributenode(), removeattributens(), removechild(), removeeventlistener(), replacechild(), setattribute(), setattributenode(), setattributenodens(), setattributens(), setuserdata ...
notificationbox - Archive of obsolete content
cation, getnotificationwithvalue, removeallnotifications, removecurrentnotification, removenotification, removetransientnotifications, attributes inherited from xul element align, allowevents, allownegativeassertions, class, coalesceduplicatearcs, collapsed, container, containment, context, contextmenu, datasources, dir, empty, equalsize, flags, flex, height, hidden, id, insertafter, insertbefore, left, maxheight, maxwidth, menu, minheight, minwidth, mousethrough, observes, ordinal, orient, pack, persist, popup, position, preference-editable, querytype, ref, removeelement, sortdirection, sortresource, sortresource2, statustext, style, template, tooltip, tooltiptext, top, uri, wait-cursor, width properties currentnotification type: notification element the currently displayed ...
...node(), comparedocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), removeattributenode(), removeattributens(), removechild(), removeeventlistener(), replacechild(), setattribute(), setattributenode(), setattributenodens(), setattributens(), setuserdata appendnotification( label , value , im...
observes - Archive of obsolete content
the id, ref, and persist attributes are not observed. element type: id the id of the broadcaster element that the observer is observing. ...
...aredocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), removeattributenode(), removeattributens(), removechild(), removeeventlistener(), replacechild(), setattribute(), setattributenode(), setattributenodens(), setattributens(), setuserdata ...
page - Archive of obsolete content
Archive › Mozilla › XUL › page
lated ] similar to a window, except it should be used for xul files that are to be loaded into an iframe. ...
...aredocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), removeattributenode(), removeattributens(), removechild(), removeeventlistener(), replacechild(), setattribute(), setattributenode(), setattributenodens(), setattributens(), setuserdata ...
popupset - Archive of obsolete content
item label="copy"/> <menuitem label="paste"/> </menupopup> </popupset> <label value="right click for popup" context="clipmenu"/> attributes inherited from xul element align, allowevents, allownegativeassertions, class, coalesceduplicatearcs, collapsed, container, containment, context, contextmenu, datasources, dir, empty, equalsize, flags, flex, height, hidden, id, insertafter, insertbefore, left, maxheight, maxwidth, menu, minheight, minwidth, mousethrough, observes, ordinal, orient, pack, persist, popup, position, preference-editable, querytype, ref, removeelement, sortdirection, sortresource, sortresource2, statustext, style, template, tooltip, tooltiptext, top, uri, wait-cursor, width properties inherited properties align, , allowevents, , boxobject, builder, , , , c...
...aredocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), removeattributenode(), removeattributens(), removechild(), removeeventlistener(), replacechild(), setattribute(), setattributenode(), setattributenodens(), setattributens(), setuserdata related elements popup, menupopup ...
preferences - Archive of obsolete content
branch; the root branch of the tree with default values. attribute nsiprefbranch2 rootbranchinternal; the root prefs branch (nsiprefbranch2). ...
...aredocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), removeattributenode(), removeattributens(), removechild(), removeeventlistener(), replacechild(), setattribute(), setattributenode(), setattributenodens(), setattributens(), setuserdata related preferences system documentat...
query - Archive of obsolete content
Archive › Mozilla › XUL › query
ing for xml queries, an xpath expression which returns results. any namespace prefixes declared on the element may be used within the expression. ...
...aredocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), removeattributenode(), removeattributens(), removechild(), removeeventlistener(), replacechild(), setattribute(), setattributenode(), setattributenodens(), setattributens(), setuserdata ...
queryset - Archive of obsolete content
| methods | related ] a container for query elements when more than one query is used. for more information, see multiple queries. ...
...aredocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), removeattributenode(), removeattributens(), removechild(), removeeventlistener(), replacechild(), setattribute(), setattributenode(), setattributenodens(), setattributens(), setuserdata ...
resizer - Archive of obsolete content
rms provide this resizing grip automatically, this type of resizer element will be hidden and ensure that the window does not get an extra resizer. ...
...aredocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), removeattributenode(), removeattributens(), removechild(), removeeventlistener(), replacechild(), setattribute(), setattributenode(), setattributenodens(), setattributens(), setuserdata ...
richlistbox - Archive of obsolete content
node(), comparedocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), removeattributenode(), removeattributens(), removechild(), removeeventlistener(), replacechild(), setattribute(), setattributenode(), setattributenodens(), setattributens(), setuserdata additemtoselection( item ) return t...
...ven item, without deselecting any other items that are already selected. appenditem( label, value ) return type: element creates a new item and adds it to the end of the existing list of items. you may optionally set a value. the function returns the newly created element. clearselection() return type: no return value deselects all of the items. a select event is sent before the items are deselected. ensureelementisvisible( element ) return type: no return value if the specified element is not currently visible to the user, the displayed items are scrolled so that it is. if the item is already visible, no scrolling occurs. ensureindexisvisible( index ) return type: no return value if the item at the specified index is not currently visible to the user the d...
row - Archive of obsolete content
Archive › Mozilla › XUL › row
e number of column elements defined in the grid. more information is available in the xul tutorial. example see grid for an example. ...
...aredocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), removeattributenode(), removeattributens(), removechild(), removeeventlistener(), replacechild(), setattribute(), setattributenode(), setattributenodens(), setattributens(), setuserdata related elements grid, columns, colu...
rows - Archive of obsolete content
Archive › Mozilla › XUL › rows
their corresponding positions between the rows. more information is available in the xul tutorial. example see grid for an example. ...
...aredocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), removeattributenode(), removeattributens(), removechild(), removeeventlistener(), replacechild(), setattribute(), setattributenode(), setattributenodens(), setattributens(), setuserdata related elements grid, columns, colu...
script - Archive of obsolete content
efault (and older) javascript version is used (like you get when including a javascript file from web content without specifying a version number). ...
...aredocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), removeattributenode(), removeattributens(), removechild(), removeeventlistener(), replacechild(), setattribute(), setattributenode(), setattributenodens(), setattributens(), setuserdata ...
scrollbox - Archive of obsolete content
ominterface.ensureelementisvisible(child_element_to_make_visible); see the nsiscrollboxobject api for other scroll-related methods. ...
...aredocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), removeattributenode(), removeattributens(), removechild(), removeeventlistener(), replacechild(), setattribute(), setattributenode(), setattributenodens(), setattributens(), setuserdata ...
scrollcorner - Archive of obsolete content
ds | related ] this element is used for the small box where the horizontal and vertical scrollbars meet. ...
...aredocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), removeattributenode(), removeattributens(), removechild(), removeeventlistener(), replacechild(), setattribute(), setattributenode(), setattributenodens(), setattributens(), setuserdata ...
separator - Archive of obsolete content
y. horizontal the separator separates vertically placed elements. vertical the separator separates horizontally placed elements. ...
...aredocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), removeattributenode(), removeattributens(), removechild(), removeeventlistener(), replacechild(), setattribute(), setattributenode(), setattributenodens(), setattributens(), setuserdata style classes the following classes may...
spacer - Archive of obsolete content
tion is available in the xul tutorial. ...
...aredocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), removeattributenode(), removeattributens(), removechild(), removeeventlistener(), replacechild(), setattribute(), setattributenode(), setattributenodens(), setattributens(), setuserdata related elements separator, splitter...
spinbuttons - Archive of obsolete content
an be increased and decreased. for instance, spinbuttons are used for the number type textbox, and with the timepicker and datepicker. ...
...aredocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), removeattributenode(), removeattributens(), removechild(), removeeventlistener(), replacechild(), setattribute(), setattributenode(), setattributenodens(), setattributens(), setuserdata ...
stack - Archive of obsolete content
Archive › Mozilla › XUL › stack
0"> <hbox flex="1"> <!-- content --> </hbox> <hbox left="0" right="200" > <!-- some content here. ...
...aredocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), removeattributenode(), removeattributens(), removechild(), removeeventlistener(), replacechild(), setattribute(), setattributenode(), setattributenodens(), setattributens(), setuserdata related deck ...
statusbar - Archive of obsolete content
left panel"/> <spacer flex="1"/> <progressmeter mode="determined" value="82"/> <statusbarpanel label="right panel"/> </statusbar> attributes inherited from xul element align, allowevents, allownegativeassertions, class, coalesceduplicatearcs, collapsed, container, containment, context, contextmenu, datasources, dir, empty, equalsize, flags, flex, height, hidden, id, insertafter, insertbefore, left, maxheight, maxwidth, menu, minheight, minwidth, mousethrough, observes, ordinal, orient, pack, persist, popup, position, preference-editable, querytype, ref, removeelement, sortdirection, sortresource, sortresource2, statustext, style, template, tooltip, tooltiptext, top, uri, wait-cursor, width properties accessibletype type: integer a value indicating the type...
...aredocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), removeattributenode(), removeattributens(), removechild(), removeeventlistener(), replacechild(), setattribute(), setattributenode(), setattributenodens(), setattributens(), setuserdata related elements statusbarpanel ...
<statusbarpanel> - Archive of obsolete content
aredocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), removeattributenode(), removeattributens(), removechild(), removeeventlistener(), replacechild(), setattribute(), setattributenode(), setattributenodens(), setattributens(), setuserdata style classes the following classes may...
... statusbarpanel-iconic use this class to have an image appear on the statusbarpanel. specify the image using the src attribute. the image will appear instead of the label. statusbarpanel-iconic-text use this class to have an image appear on the statusbarpanel as well as a text label. specify the image using the src attribute. specify the text using the label attribute. the image will appear before the label. statusbarpanel-menu-iconic use this class to have an image appear on the statusbarpanel, and also allow a popup menu. specify the image using the src attribute, and place a menupopup element inside the statusbarpanel. the image will appear instead of the label. related elements statusbar ...
stringbundle - Archive of obsolete content
ring, getstring examples (example needed) attributes src type: uri the uri of the property file that contains the localized strings. ...
...aredocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), removeattributenode(), removeattributens(), removechild(), removeeventlistener(), replacechild(), setattribute(), setattributenode(), setattributenodens(), setattributens(), setuserdata related xul property files ...
stringbundleset - Archive of obsolete content
[ examples | attributes | properties | methods | related ] a container for stringbundle elements. ...
...aredocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), removeattributenode(), removeattributens(), removechild(), removeeventlistener(), replacechild(), setattribute(), setattributenode(), setattributenodens(), setattributens(), setuserdata ...
tabbrowser - Archive of obsolete content
node(), comparedocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), removeattributenode(), removeattributens(), removechild(), removeeventlistener(), replacechild(), setattribute(), setattributenode(), setattributenodens(), setattributens(), setuserdata addprogresslistener( listener ) ...
.... removetabsprogresslistener( listener ) return type: no return value removes a progress listener to the browser which has been monitoring all tabs. the progress listener should implement the nsiwebprogresslistener interface. replacegroup( group ) not in firefox return type: array of session history objects replaces existing tabs with a new set. if there were more tabs before, the additional ones are not removed. you can use the removetab method to remove the existing tabs first if that is desired. 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 method returns an ar...
tabpanel - Archive of obsolete content
nd you may just use any other container in place of it. more information is available in the xul tutorial. ...
...aredocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), removeattributenode(), removeattributens(), removechild(), removeeventlistener(), replacechild(), setattribute(), setattributenode(), setattributenodens(), setattributens(), setuserdata related elements tabbox, tabs, tab, ...
tabpanels - Archive of obsolete content
ple needed) attributes selectedindex type: integer gets and sets the index of the currently selected panel. the first item is at index 0. ...
...aredocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), removeattributenode(), removeattributens(), removechild(), removeeventlistener(), replacechild(), setattribute(), setattributenode(), setattributenodens(), setattributens(), setuserdata related elements tabbox, tabs, tab, ...
template - Archive of obsolete content
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. ...
...aredocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), removeattributenode(), removeattributens(), removechild(), removeeventlistener(), replacechild(), setattribute(), setattributenode(), setattributenodens(), setattributens(), setuserdata ...
textbox - Archive of obsolete content
autocapitalize, and autocorrect attributes too! added from david walsh's article on spell check. 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. timeout type: integer for autocomplete textboxes, the number of milliseconds before the textbox starts searching for completions. the default is 50 milliseconds. for search textboxes, the number of milliseconds before the timer fires a command event. the default is 500 milliseconds. for timed textboxes, the number of milliseconds before the timer fires a command event. there is no default. the timer starts after the user types a character. if the user types another character, th...
...aredocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), removeattributenode(), removeattributens(), removechild(), removeeventlistener(), replacechild(), setattribute(), setattributenode(), setattributenodens(), setattributens(), setuserdata style classes the following classes may...
textnode - Archive of obsolete content
ue examples (example needed) attributes value type: uri the text value to display. this value should be an rdf property (predicate). ...
...aredocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), removeattributenode(), removeattributens(), removechild(), removeeventlistener(), replacechild(), setattribute(), setattributenode(), setattributenodens(), setattributens(), setuserdata ...
titlebar - Archive of obsolete content
properti...
...aredocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), removeattributenode(), removeattributens(), removechild(), removeeventlistener(), replacechild(), setattribute(), setattributenode(), setattributenodens(), setattributens(), setuserdata ...
toolbargrippy - Archive of obsolete content
ly when modifying its theme. more information is available in the xul tutorial. ...
...aredocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), removeattributenode(), removeattributens(), removechild(), removeeventlistener(), replacechild(), setattribute(), setattributenode(), setattributenodens(), setattributens(), setuserdata related elements toolbar, toolbarbut...
toolbaritem - Archive of obsolete content
barbutton-1" label="label1" /> <toolbarbutton id="myext-button2" class="toolbarbutton-1" label="labe2l" /> </toolbaritem> attributes inherited from xul element align, allowevents, allownegativeassertions, class, coalesceduplicatearcs, collapsed, container, containment, context, contextmenu, datasources, dir, empty, equalsize, flags, flex, height, hidden, id, insertafter, insertbefore, left, maxheight, maxwidth, menu, minheight, minwidth, mousethrough, observes, ordinal, orient, pack, persist, popup, position, preference-editable, querytype, ref, removeelement, sortdirection, sortresource, sortresource2, statustext, style, template, tooltip, tooltiptext, top, uri, wait-cursor, width properties inherited properties align, , allowevents, , boxobject, builder, , , , c...
...aredocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), removeattributenode(), removeattributens(), removechild(), removeeventlistener(), replacechild(), setattribute(), setattributenode(), setattributenodens(), setattributens(), setuserdata related elements toolbar, toolbarbut...
toolbarpalette - Archive of obsolete content
label="&mylabel;" tooltiptext="&mytiptext;" oncommand="somefunction()"/> </toolbarpalette> attributes inherited from xul element align, allowevents, allownegativeassertions, class, coalesceduplicatearcs, collapsed, container, containment, context, contextmenu, datasources, dir, empty, equalsize, flags, flex, height, hidden, id, insertafter, insertbefore, left, maxheight, maxwidth, menu, minheight, minwidth, mousethrough, observes, ordinal, orient, pack, persist, popup, position, preference-editable, querytype, ref, removeelement, sortdirection, sortresource, sortresource2, statustext, style, template, tooltip, tooltiptext, top, uri, wait-cursor, width properties inherited properties align, , allowevents, , boxobject, builder, , , , c...
...aredocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), removeattributenode(), removeattributens(), removechild(), removeeventlistener(), replacechild(), setattribute(), setattributenode(), setattributenodens(), setattributens(), setuserdata related elements toolbar, toolbarbut...
toolbarseparator - Archive of obsolete content
toolbar> <toolbarbutton label="button 1"/> <toolbarseparator /> <toolbarbutton label="button 2"/> </toolbar> </toolbox> attributes inherited from xul element align, allowevents, allownegativeassertions, class, coalesceduplicatearcs, collapsed, container, containment, context, contextmenu, datasources, dir, empty, equalsize, flags, flex, height, hidden, id, insertafter, insertbefore, left, maxheight, maxwidth, menu, minheight, minwidth, mousethrough, observes, ordinal, orient, pack, persist, popup, position, preference-editable, querytype, ref, removeelement, sortdirection, sortresource, sortresource2, statustext, style, template, tooltip, tooltiptext, top, uri, wait-cursor, width properties accessibletype type: integer a value indicating the type...
...aredocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), removeattributenode(), removeattributens(), removechild(), removeeventlistener(), replacechild(), setattribute(), setattributenode(), setattributenodens(), setattributens(), setuserdata related elements toolbar, ...
toolbarset - Archive of obsolete content
fox only this element is used as a container for custom toolbars, which are added in the custom toolbar dialog. ...
...aredocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), removeattributenode(), removeattributens(), removechild(), removeeventlistener(), replacechild(), setattribute(), setattributenode(), setattributenodens(), setattributens(), setuserdata related elements toolbar, ...
toolbarspacer - Archive of obsolete content
rties | methods | related ] firefox only a space between toolbar items. ...
...aredocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), removeattributenode(), removeattributens(), removechild(), removeeventlistener(), replacechild(), setattribute(), setattributenode(), setattributenodens(), setattributens(), setuserdata related elements toolbar, toolbarbut...
toolbarspring - Archive of obsolete content
ds | related ] firefox only a flexible space between toolbar items. ...
...aredocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), removeattributenode(), removeattributens(), removechild(), removeeventlistener(), replacechild(), setattribute(), setattributenode(), setattributenodens(), setattributens(), setuserdata related elements toolbar, ...
toolbox - Archive of obsolete content
</toolbar> </toolbox> <textbox multiline="true" value="we have two toolbars inside of one toolbox above." width="20"/> </window> attributes inherited from xul element align, allowevents, allownegativeassertions, class, coalesceduplicatearcs, collapsed, container, containment, context, contextmenu, datasources, dir, empty, equalsize, flags, flex, height, hidden, id, insertafter, insertbefore, left, maxheight, maxwidth, menu, minheight, minwidth, mousethrough, observes, ordinal, orient, pack, persist, popup, position, preference-editable, querytype, ref, removeelement, sortdirection, sortresource, sortresource2, statustext, style, template, tooltip, tooltiptext, top, uri, wait-cursor, width properties accessible type: nsiaccessible returns the accessibil...
...node(), comparedocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), removeattributenode(), removeattributens(), removechild(), removeeventlistener(), replacechild(), setattribute(), setattributenode(), setattributenodens(), setattributens(), setuserdata appendcustomtoolbar( name, currentset ...
tree - Archive of obsolete content
Archive › Mozilla › XUL › tree
aredocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), removeattributenode(), removeattributens(), removechild(), removeeventlistener(), replacechild(), setattribute(), setattributenode(), setattributenodens(), setattributens(), setuserdata startediting( row, column ) return typ...
... <treeitem> <treerow> <treecell value="false"/> <treecell label="alice"/> </treerow> </treeitem> <treeitem> <treerow> <treecell value="false"/> <treecell label="bob"/> </treerow> </treeitem> </treechildren> </tree> </window> css: treechildren::-moz-tree-checkbox { /* unchecked checkbox treecells. this style must come before treechildren::-moz-tree-checkbox(checked) otherwise it won't take effect. */ list-style-image: url("") } treechildren::-moz-tree-checkbox(checked) { /* checked checkbox treecells. cbox-check.gif isn't available in firefox 1, 2, and 3 in mac os x so you should specify a url to an image in your extension or elsewhere. */ list-style-image: url("chrome://global/skin/checkbox/cbox-chec...
treechildren - Archive of obsolete content
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. ...
...aredocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), removeattributenode(), removeattributens(), removechild(), removeeventlistener(), replacechild(), setattribute(), setattributenode(), setattributenodens(), setattributens(), setuserdata example <tree flex="1"> <treecols> ...
treecol - Archive of obsolete content
col.type). 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 { /* unchecked checkbox treecells. this style must come before treechildren::-moz-tree-checkbox(checked) otherwise it won't take effect. */ list-style-image: none; } treechildren::-moz-tree-checkbox(checked){ /* css for checked cells. cbox-check.gif isn't available in firefox 1, 2, and 3 on mac os x, so you should specify a url to an image in your extension or elsewhere. */ list-style-image: url("chrome://global/skin/checkbox/cbox-check.gif"); }...
...aredocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), removeattributenode(), removeattributens(), removechild(), removeeventlistener(), replacechild(), setattribute(), setattributenode(), setattributenodens(), setattributens(), setuserdata style classes the following class may b...
treecols - Archive of obsolete content
pe examples (example needed) attributes pickertooltiptext type: string the text for the tooltip on the column picker. ...
...aredocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), removeattributenode(), removeattributens(), removechild(), removeeventlistener(), replacechild(), setattribute(), setattributenode(), setattributenodens(), setattributens(), setuserdata related elements tree, treecol, tree...
treerow - Archive of obsolete content
ated 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. ...
...aredocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), removeattributenode(), removeattributens(), removechild(), removeeventlistener(), replacechild(), setattribute(), setattributenode(), setattributenodens(), setattributens(), setuserdata related elements tree, treecols, tre...
treeseparator - Archive of obsolete content
ated 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. ...
...aredocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), removeattributenode(), removeattributens(), removechild(), removeeventlistener(), replacechild(), setattribute(), setattributenode(), setattributenodens(), setattributens(), setuserdata related elements tree, treecols, tre...
triple - Archive of obsolete content
is 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. ...
...aredocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), removeattributenode(), removeattributens(), removechild(), removeeventlistener(), replacechild(), setattribute(), setattributenode(), setattributenodens(), setattributens(), setuserdata ...
vbox - Archive of obsolete content
Archive › Mozilla › XUL › vbox
tutorial. ...
...aredocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), removeattributenode(), removeattributens(), removechild(), removeeventlistener(), replacechild(), setattribute(), setattributenode(), setattributenodens(), setattributens(), setuserdata related elements box, hbox ...
Application Update - Archive of obsolete content
ate" link // supplied in the "an update is available" page of the update wizard. pref("app.update.url.details", "http://yourserver.net/yourpage"); // user-settable override to app.update.url for testing purposes. ...
...to app.update.url for testing purposes. //pref("app.update.url.override", ""); // interval: time between checks for a new version (in seconds) // default=1 day pref("app.update.interval", 86400); // interval: time before prompting the user to download a new version that // is available (in seconds) default=1 day pref("app.update.nagtimer.download", 86400); // interval: time before prompting the user to restart to install the latest // download (in seconds) default=30 minutes pref("app.update.nagtimer.restart", 1800); // interval: when all registered timers should be checked (in milliseconds) // default=5 seconds pref("app.update.timer", 600000); // whether or not we show a dialog box informing the user that the update was // successfully applied. this...
MacFAQ - Archive of obsolete content
completed a xulrunner build, you should copy or symlink the dist/xul.framework directory to /library/frameworks. note that in order to copy the framework while keeping the relative soft-links in the framework, do something like: % ( cd dist ; gnutar cf - xul.framework | ( cd /library/frameworks ; gnutar xf - )) installing your application your application must be installed as a xulrunner app before you can open it. to do this, type: xulrunner-bin --install-app /path/to/appdir note the path to your application must end with the directory containing application.ini; you should not reference application.ini in this command. this command will place a copy of your application in /applications/(vendor)/(name) , where (vendor) is the vendor field in your application.ini and (name) is the name fiel...
...mmand-line trapping when the app is already running, without getting into appleevents or c++ code. this is implemented in a pseudo "hidden window" technique and parsing the window arguments instead of command-line handlers and some of the toolkit singleton window code. ...
Gecko Compatibility Handbook - Archive of obsolete content
ble browser, developed as part of the mozilla open source project and based on w3 standards rather than the proprietary approaches of the past. adhering to web standards simplifies cross-browser web development and enables accessibility. 4.x vs. gecko since 1997, much of the web's content has been developed for microsoft internet explorer 4 or netscape navigator 4. these browsers were developed before the relevant w3c recommendations for html, css, and the dom existed. these earlier, non-standards based browsers differed in several ways from gecko: these browsers use proprietary (non-standard) html, css, and javascript. internet explorer 4 and netscape navigator 4 share support for a large part of the html 3.2 standard and basic javascript. while they support the css 1 standard to some d...
... the css styles. incorrect use of xml empty tag notation many authors have taken to using xml empty tag notation (<tag />) in their html files. in xml, an empty tag never has any content. the xhtml backward compatibility guidelines state that empty elements can be coded by following the tag name with a space followed with as slash as in <tag />. to be backwardly compatible you must have a space before the trailing />. in addition, you must only use the xml empty tag notation for html elements that are always empty - and not for html elements that have optional ending tags. for example, it is ok to code <br> as <br /> although there is no benefit to do so in html documents. but it is not ok to code <option> as <option />. to understand why, consider the following: html without option...
2006-10-06 - Archive of obsolete content
hence, they are looking for a mac user to test out the new features by building a mac.rdf file with all of the various .mac account properties mentioned in the document here. ...
... down architectural description of tb's data structures along with documentation about extracting them. brian king also mentions that documentation on handling message headers on the ui side would be helpful. cédric corazza recommends that the proposed documention should be made available on the l10n cvs once it reaches a decent stage so that localizers can get a head-start on the localization before the final version is made available. updated : need ui to rearrange tags peter lairo suggested some ui should be available for rearranging tags. related: bug 342065 meetings none for this week. ...
2006-10-27 - Archive of obsolete content
r to cédric corazza posting. cédric's posting was about a french site which had already announced the availablity of ff 2.0 final release and provided download links, even though the release was on october 24. the owner of the site probably browsed on the releases/2.0 dir on the ftp and got the releases, which is kind of unpolite. ...
...paul suggested that the best way to deal with this would be to ask people to wait, and let them know that they're degrading their user experience. ...
2006-11-03 - Archive of obsolete content
v.security - october 28, 2006 to november 3, 2006 return to mozilla-dev-security announcements none during this week. discussions extended validation certificates major discussion this week started by gervase markham about security certificates, more specifically extended validation certificates. the aim of the group is to develop a new, higher standard for the validation which is done before certificate issuance, called extended validation. the idea was that such certs would be presented differently in the ui, to give the cas a reason to go to the extra effort, and to give customers a reason to buy them. in ie 7 at least, the use of an ev certificate is tied to the green background in the url bar. a decision has to be made as to the usefulness of extended validation certificates an...
... ev certificate is tied to the green background in the url bar. a decision has to be made as to the usefulness of extended validation certificates and weather or not they will make a difference to the reliability of information in certificates. if it does make a difference, does it warrant a different ui presentation for these certificates (ie the green bar). he would like to have some comments before november 19th, after which there will possibly be a vote. all questions about the cabf are welcome. more information about ca can be found at http://www.cabforum.org/ meetings none during this week. ...
Building a Theme - Archive of obsolete content
ude a closing slash and remove any trailing spaces. save the file with the id of your theme as its name (e.g. sample@example.net). no file extension. now you should be ready to test your theme! start firefox. firefox will detect the text link to your theme directory and install the theme. your theme will not be active the first time you install, and you will need to click "enable" and restart before you can see your change. after it restarts this second time, you should see the background color of the toolbars is displayed in orange now. you can now go back and make additional changes to your css files, close and restart firefox, and see the updates. package now that your theme works, you can package it for deployment and installation. zip up the contents of your theme's folder (not th...
... now upload the .xpi file to your server, making sure it's served as application/x-xpinstall. you can link to it and allow people to download and install it. for the purposes of just testing our .xpi file we can just drag it into the add-ons manager via "tools -> add-ons manager", or open it using "file -> open file...". installing from a web page there are a var...
Browser Detection and Cross Browser Support - Archive of obsolete content
re oriented object detection object detection is a powerful method of providing cross browser support in your web content. although you can use object detection as just another means of distinguishing between vendor/version the technique shows it's true power when used to detect features rather than browsers. feature oriented object detection is the testing for the existence of specific objects before attempting to use them in a script. the classic example is: if (document.images) { // code which processes the images } the advantage to feature detection is that it will work regardless of the vendor/version. we can rewrite the earlier example which illustrated problems with using objects to determine vendor/version to use feature detection instead. if (document.body && typeof(document.bod...
..., 0.9.4.1, 0.9.4.2 is minor. note: the branch tag is a string and can contain more than single digits in any particular level. for example, it is conceivable that someday there will exist branch tags similar to 2.2.0 and 2.12.36. since these values are strings, it is not possible to use relative string comparisons to determine which branch tag came later. in our example, branch 2.2.0 was created before 2.12.36 however comparing these values as strings shows '2.2.0' > '2.12.36'. the javascript function geckogetrv() provides one solution to this problem by converting the branch tag in the user agent string into a floating point number where each level of the branch tag is considered as a number from 0-99. geckogetrv() examples branch tag geckogetrv() 0.9.2 0.0902 ...
-ms-hyphenate-limit-chars - Archive of obsolete content
the -ms-hyphenate-limit-chars css property is a microsoft extension that specifies one to three values indicating the minimum number of characters in a hyphenated word. if the word does not meet the required minimum number of characters in the word, before the hyphen, or after the hyphen, then the word is not hyphenated. ...
...ers in a hyphenated word. if the word does not meet the required minimum number of characters in the word, before the hyphen, or after the hyphen, then the word is not hyphenated. initial valueautoapplies toall elementsinheritedyescomputed valueas specifiedanimation typediscrete syntax values auto corresponds to a value of 5 2 2, indicating a 5-character word limit, 2 characters required before a hyphenation break, and 2 characters required following a hyphenation break. <integer>{1,3} one to three integer values, corresponding to the word limit, the minimum number of characters required before a hyphenation break, and the minimum number of characters required following a hyphenation break, respectively. if the third value is missing it is equal to the second. if the second an...
CSS - Archive of obsolete content
Archive › Web › CSS
n that gets or sets a value indicating whether to override any css properties that would have been set in high contrast mode.-ms-hyphenate-limit-charsthe -ms-hyphenate-limit-chars css property is a microsoft extension that specifies one to three values indicating the minimum number of characters in a hyphenated word. ...
...n the track of a slider control to alter its numerical value. a slider control is one possible representation of <input type="range">.::-ms-ticks-afterthe ::-ms-ticks-after css pseudo-element is a microsoft extension that applies one or more styles to the tick marks that appear after the track of a slider control. a slider control is one possible representation of <input type="range">.::-ms-ticks-beforethe ::-ms-ticks-before css pseudo-element is a microsoft extension that applies one or more styles to the tick marks that appear before the track of a slider control. a slider control is one possible representation of <input type="range">.::-ms-tooltipthe ::-ms-tooltip css pseudo-element is a microsoft extension that represents the tooltip of a slider control. a slider control is one possible repr...
Processing XML with E4X - Archive of obsolete content
. since a greater than sign is not escaped, it is possible to get an xml error if the cdata closing sequence (]]>) is included. it is not possible to directly interpolate variables amidst other literal (or variable) attribute content, however (e.g., bar="a{var1}{var2}"). one must instead either calculate the variable with a javascript expression (e.g., bar={'a'+var1+var2}), define a new variable before the element literal which includes the full interpolation and then include that variable or retrieve the attribute after the literal to alter it (see below). while one can interpolate attribute names as well as attribute values: var a = 'att'; var b = <b {a}='value'/>; alert(b); // gives: <b att="value"/> ...one cannot interpolate a whole expression at once (e.g., <b {a}>.) after executing t...
.../ alerts 3 searching and filtering e4x provides special operators for selecting nodes within a document that match specific criteria. these filter operations are specified using an expression contained in parentheses: var html = <html> <p id="p1">first paragraph</p> <p id="p2">second paragraph</p> </html>; alert(html.p.(@id == "p1")); // alerts "first paragraph" nodes matching the path before the expression (in this case the paragraph elements) are added to the scope chain before the expression is evaluated, as if they had been specified using the with statement. consequently, filters can also run against the value of a single node contained within the current element: var people = <people> <person> <name>bob</name> <age>32</age> </person> <person> <name>joe</name>...
Mozilla's DOCTYPE sniffing - Archive of obsolete content
n". the public identifier "-//w3c//dtd xhtml 1.0 strict//en". the public identifier "iso/iec 15445:2000//dtd hypertext markup language//en". the public identifier "iso/iec 15445:2000//dtd html//en". the public identifier "-//ietf//dtd html i18n//en". almost standards mode the following trigger almost standards mode. almost standards mode was created after 1.0 and 1.1alpha, but before 1.0.1 and 1.1beta. before almost standards mode was created these doctypes triggered full standards mode. the public identifier "-//w3c//dtd xhtml 1.0 transitional//en". the public identifier "-//w3c//dtd xhtml 1.0 frameset//en". the public identifier "-//w3c//dtd html 4.01 transitional//en", with a system identifier. the public identifier "-//w3c//dtd html 4.01 frameset//en", with a system...
...l declaration (pseudo-pi) without a doctype (in other words, ignore the xml declaration and use the doctype). in 1.0 and 1.1alpha and earlier (but not in 1.0.1 or 1.1beta), the presence of an xml declaration triggered full standards mode. a doctype declaration that cannot be understood (e.g., no matching quote). the system identifier "http://www.ibm.com/data/dtd/v11/ibmxhtml1-transitional.dtd" (before 1.5b and 1.4.2, this triggered almost standards mode). the public identifier "-//w3c//dtd html 4.01 transitional//en", without a system identifier. the public identifier "-//w3c//dtd html 4.01 frameset//en", without a system identifier. the public identifier "-//w3c//dtd html 4.0 transitional//en" (see also test with a system identifier). the public identifier "-//w3c//dtd html 4.0 frameset//...
Building up a basic demo with A-Frame - Game development
suitable for your scene — milimeters, meters, feet, or miles — it's up to you. adding a background: sky box a sky box is a background for the 3d world, represented by an <a-sky> element. in our case we will use a simple color, but it could also be an image, etc. looking around would give an impression of being inside an open sky, a wooden barn — wherever you like! add the following html before the <a-cube> element: <a-sky color="#dddddd"></a-sky> at this point, if you save the code and refresh your browser you can already see the cube on the screen with our custom background: here's the code we have created so far: you can also check it out on github. a-frame takes care of setting up everything you need: a default light source and camera are included, so the cube is visibl...
...orner of the screen, to allow you to shift to full screen, stereoscopic image viewing if you have the necesary vr hardware set up and ready. specifying a camera a camera entity can be created by adding an <a-camera> element to the scene. we can set the position of the camera explicitly and move it back a little bit from the center of the scene, so we'll be able to see the shapes. ...
Building up a basic demo with the PlayCanvas engine - Game development
e document <title>, and some css to set the width and height of the <canvas> element that playcanvas will use to 100% so that it will fill the entire available viewport space. the first <script> element includes the playcanvas library in the page; we will write our example code in the second one. there is one helper variable already included, which will store a reference to the <canvas> element. before reading on, copy this code to a new text file and save it in your working directory as index.html. playcanvas application to begin developing our game we have to create the playcanvas application first (using the given <canvas> element), and then start the update loop. add the following code to the bottom of your second <script> element: var app = new pc.application(canvas); app.start(); the...
...linder.addcomponent("model", { type: "cylinder" }); app.root.addchild(cylinder); cylinder.rotate(15, 0, 0); this looks very similar to the code we used for creating a cube, but instead of the box component we are adding a cylinder. it is also rotated around the x axis to show it's actually a 3d shape. to make the cylinder have a color, let's say yellow, we need to create the material for it, as before. add the following lines: var cylindermaterial = new pc.phongmaterial(); cylindermaterial.diffuse.set(1, 0.58, 0); cylindermaterial.update(); cylinder.model.model.meshinstances[0].material = cylindermaterial; cone creating a cone and its material is done in almost exacly the same way as we did for the cylinder. add the following code, again, at the bottom of your script: var cone = new pc.en...
Building up a basic demo with Three.js - Game development
ike the document <title>, and some css to set the width and height of the <canvas> element, that three.js will insert on the page to 100% to fill the entire available viewport space. the first <script> element includes the three.js library in the page, and we will write our example code inside the second. there are two helper variables already included, which store the window's width and height. before reading further, copy this code to a new text file, and save it in your working directory as index.html. renderer a renderer is a tool which displays scenes right in your browser. there are a few different renderers: webgl is the default, and others you can use are canvas, svg, css, and dom. they differ in how everything is rendered, so the webgl implementation will implement differently than t...
...mationframe() invocation inside the render function: cube.rotation.y += 0.01; this rotates the cube on every frame, by a tiny bit, so the animation looks smooth. scaling we can also scale an object. applying a constant value, we would make it grow, or shrink just once. let's make things more interesting. first, we implement a helper variable, called t, for counting elapsed time. add it right before the render() function: var t = 0; now let's increase the value by a given constant value, on each frame of the animation. add the following lines, just below the requestanimationframe() invocation: t += 0.01; torus.scale.y = math.abs(math.sin(t)); we use math.sin, ending up with quite an interesting result. this scales the torus, repeating the process, as sin is a periodic function. we're w...
Desktop mouse and keyboard controls - Game development
er: if(event.keycode == keyboardhelper.left) { leftpressed = true; } note: you can also find a list if the different keycodes and what keys they relate to in the keycode reference page. you can see this example in action online at end3r.github.io/javascript-game-controls and the full source code can be found at github.com/end3r/javascript-game-controls. phaser approach as i mentioned before you can write everything on your own, but you can also take the advantage of built-in functions in frameworks like phaser — these will make your life easier and development a lot faster. all the edge cases, differences between browser implementations, etc. are handled by the framework, so you can focus on the actual task you want to do. mouse the mouse interactions in the game are focused on ...
...intro') { this.hideintro(); } }; this hides the intro and starts the actual game, without us having to set up another new key control just for this. pause and game over screens to make the game fully playable with keyboard it should be possible to go back to the main menu, continue playing, or restart the game from the pause and game over screens. it can be done exactly the same as before — by capturing key codes and performing actions. for example, by specifying phaser.keycode.backspace or phaser.keycode.delete you can hook up an action to fire when the delete/backspace button is pressed. summary ok, we've dealt with touch, keyboard and mouse controls. now let's move on to look at how to set up the game to be controlled using a console gamepad, using the gamepad api. pr...
Unconventional controls - Game development
orking examples you can look at. to get the leap motion working on your computer you have to first install it by following the steps at leapmotion.com/setup. when everything is installed and the controller is connected to your computer we can proceed with implementing support in our little demo. first, we add a <script> tag with the url pointing at this file, and add <div id="output"></div> just before the closing </body> tag for outputting diagnostic information. we will need a few helper variables for our code to work — one for the purpose of calculating the degrees from radians, two for holding the horizontal and vertical amount of degrees our hand is leaning above the controller, one for the threshold of that lean, and one for the state of our hand's grab status. we next add these lines ...
...tion. we will need a few helper variables for our code to work — one for the purpose of calculating the degrees from radians, two for holding the horizontal and vertical amount of degrees our hand is leaning above the controller, one for the threshold of that lean, and one for the state of our hand's grab status. ...
Efficient animation for web games - Game development
en your dom animations absolutely must synchronise with canvas content animations, do make sure to use window.requestanimationframe, and not older methods such as window.settimeout. assuming you are running in an arbitrary browsing session, you can never really know how long the browser will take to draw a particular frame. requestanimationframe causes the browser to redraw and call your function before that frame gets to the screen. the downside of using this vs. settimeout is that your animations must be time-based instead of frame-based, i.e. you must keep track of time and set your animation properties based on elapsed time. requestanimationframe includes a domhighrestimestamp in its callback function prototype, which you definitely should use (as opposed to using the date object), as this w...
...imation); you will note that we set starttime to -1 at the beginning, when we could just as easily have set the time using the date() object and avoided the extra code in the animation callback. we do this so that any setup or processes that happen between the start of the animation and the callback being processed do not affect the start of the animation, and so that all the animations we start before the frame is processed are synchronised. to save battery life, it is best to only draw when there are things going on, so that would mean calling requestanimationframe (or your refresh function, which in turn calls that) in response to events happening in your game. unfortunately, this makes it very easy to end up drawing things multiple times per frame. we would recommend keeping track of when ...
Create the Canvas and draw on it - Game development
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. ...
... the most important part of the code above is the arc() method. it takes six parameters: x and y coordinates of the arc's center arc radius start angle and end angle (what angle to start and finish drawing the circle, in radians) direction of drawing (false for clockwise, the default, or true for anti-clockwise.) this last parameter is optional. the fillstyle property looks different than before. this is because, just as with css, color can be specified as a hexadecimal value, a color keyword, the rgba() function, or any of the other available color methods. instead of using fill() and filling the shapes with colors, we can use stroke() to only colour the outer stroke. try adding this code to your javascript too: ctx.beginpath(); ctx.rect(160, 10, 100, 40); ctx.strokestyle = "rgba(0, 0...
Buttons - Game development
startbutton.destroy(); ball.body.velocity.set(150, -150); playing = true; } when the button is pressed, we remove the button, sets the ball's initial velocity and set the playing variable to true. finally for this section, go back into your create() function, find the ball.body.velocity.set(150, -150); line, and remove it. you only want the ball to move when the button is pressed, not before! keeping the paddle still before the game starts it works as expected, but we can still move the paddle when the game hasn't started yet, which looks a bit silly. to stop this, we can take advantage of the playing variable and make the paddle movable only when the game has started. to do that, adjust the update() function like so: function update() { game.physics.arcade.collide(ball, paddl...
...le movable only when the game has started. to do that, adjust the update() function like so: function update() { game.physics.arcade.collide(ball, paddle, ballhitpaddle); game.physics.arcade.collide(ball, bricks, ballhitbrick); if(playing) { paddle.x = game.input.x || game.world.width*0.5; } } that way the paddle is immovable after everything is loaded and prepared, but before the start of the actual game. compare your code you can check the finished code for this lesson in the live demo below, and play with it to understand better how it works: next steps the last thing we will do in this article series is make the gameplay even more interesting by adding some randomization to the way the ball bounces off the paddle. « previousnext » ...
Visual-js game engine - Game development
file in this project has its own license , be careful , do not violate the basic rules. 2) you are free to use any version of visual js library in any other project (even commercial projects) as long as the copyright header is left intact except for plugins on sale and graphics that come with them (they have special commercial licence). 3) please read the following terms and conditions before using this application: disclaimer of warranty 'visual js' is provided "as-is" and without warranty of any kind, express, implied or otherwise, including without limitation, any warranty of merchantability or fitness for a particular purpose. in no event shall the author of this software be held liable for data loss, damages, loss of profits or any other kind of...
...ame object (form dialog for define type of new game object ) add->quick code (make your work faster - add usually code blocks) resources - explorer view for images and audios , you can drag or edit also need to execute node build_resources for creating resources object for engine. inserting new code will be always at current line selected intro editor . save on drop menu or better with ctrl+s before testing in browsers. adding new script explanation : after adding new script and save script if you have extra changes , open starter/run.js and you will found line : sys.script.load("scripts/new_script.js") ctrl+s use from menu run->choose browser for testing . - important safari not working at the moment chrome , firefox , opera tutorial - pencil (animation path) : how to use...
TCP handshake - MDN Web Docs Glossary: Definitions of Web-related terms
tcp/ip connection over an ip based network. the three messages transmitted by tcp to negotiate and start a tcp session are nicknamed syn, syn-ack, and ack for synchronize, synchronize-acknowledgement, and acknowledge respectively. ...
...the connection can be terminated independently by each side of the connection via a four-way handshake. ...
HTML: A good basis for accessibility - Learn web development
in case so-called alt text is not available, but also making sure that alt text is provided in alt attributes wherever possible. note that the contents of the alt attribute should always provide a direct representation of the image and what it conveys visually. any personal knowledge or extra description shouldn't be included here, as it is not useful for people who have not come across the image before. one thing to consider is whether your images have meaning inside your content, or whether they are purely for visual decoration, and thus have no meaning. if they are decorational, it is better to write an empty text as a value for alt attribute (see empty alt attributes) or to just include them in the page as css background images. note: read images in html and responsive images for a lot mo...
... and may accidentally activate the wrong interactive content while navigating. spacing may be created using css properties such as margin. hand tremors and the giant-button-problem - axess lab test your skills! you've reached the end of this article, but can you remember the most important information? see test your skills: html accessibility to verify that you've retained this information before you move on. summary you should now be well-versed in writing accessible html for most occasions. our wai-aria basics article will help to fill gaps in this knowledge, but this article has taken care of the basics. next up we'll explore css and javascript, and how accessibility is affected by their good or bad use. previous overview: accessibility next in this module what is access...
HTML: A good basis for accessibility - Learn web development
in case so-called alt text is not available, but also making sure that alt text is provided in alt attributes wherever possible. note that the contents of the alt attribute should always provide a direct representation of the image and what it conveys visually. any personal knowledge or extra description shouldn't be included here, as it is not useful for people who have not come across the image before. one thing to consider is whether your images have meaning inside your content, or whether they are purely for visual decoration, and thus have no meaning. if they are decorational, it is better to write an empty text as a value for alt attribute (see empty alt attributes) or to just include them in the page as css background images. note: read images in html and responsive images for a lot mo...
... and may accidentally activate the wrong interactive content while navigating. spacing may be created using css properties such as margin. hand tremors and the giant-button-problem - axess lab test your skills! you've reached the end of this article, but can you remember the most important information? see test your skills: html accessibility to verify that you've retained this information before you move on. summary you should now be well-versed in writing accessible html for most occasions. our wai-aria basics article will help to fill gaps in this knowledge, but this article has taken care of the basics. next up we'll explore css and javascript, and how accessibility is affected by their good or bad use. previous overview: accessibility next in this module what is access...
Debugging CSS - Learn web development
and you can try out some different colors; these will update in real time on the page. in a similar fashion, you could change the width or style of the border. adding a new property you can add properties using the devtools. perhaps you have realised that you don't want your box to inherit the <body> element's font size, and want to set its own specific size? you can try this out in devtools before adding it to your css file. you can click the closing curly brace in the rule to start entering a new declaration into it, at which point you can start typing the new property and devtools will show you an autocomplete list of matching properties. after selecting font-size, enter the value you want to try. you can also click the + button to add an additional rule with the same selector, and add ...
...h information to be able to search for likely sounding problems and workarounds. if you are still struggling to fix the problem then having a reduced test case gives you something to ask for help with, by posting to a forum, or showing to a co-worker. you are much more likely to get help if you can show that you have done the work of reducing the problem and identifying exactly where it happens, before asking for help. a more experienced developer might be able to quickly spot the problem and point you in the right direction, and even if not, your reduced test case will enable them to have a quick look and hopefully be able to offer at least some help. in the instance that your problem is actually a bug in a browser, then a reduced test case can also be used to file a bug report with the relev...
Images, media, and form elements - Learn web development
xtarea { font-family: inherit; font-size: 100%; box-sizing: border-box; padding: 0; margin: 0; } textarea { overflow: auto; } note: normalizing stylesheets are used by many developers to create a set of baseline styles to use on all projects. typically these do similar things to those described above, making sure that anything different across browsers is set to a consistent default before you do your own work on the css. they are not as important as they once were, as browsers are typically more consistent than in the past. however if you want to take a look at one example, check out normalize.css, which is a very popular stylesheet used as a base by many projects. for further information on styling forms, take a look at the two articles in the html section of these guides. s...
...pular stylesheet used as a base by many projects. for further information on styling forms, take a look at the two articles in the html section of these guides. styling web forms advanced form styling test your skills! we have covered a lot in this article, but can you remember the most important information? you can find some further tests to verify that you've retained this information before you move on — see test your skills: images and form elements. summary this lesson has highlighted some of the differences you will encounter when working with images, media, and other unusual elements in css. in the next article we'll look over a few tips you'll find useful when you have to style html tables. previous overview: building blocks next in this module cascade and inhe...
Styling tables - Learn web development
ion-side: bottom; color: #666; text-align: right; letter-spacing: 1px; } there is nothing remarkable here, except for the caption-side property, which has been given a value of bottom. this causes the caption to be positioned on the bottom of the table, which along with the other declarations gives us this final look (see it live at punk-bands-complete.html): table styling quick tips before moving on, we thought we'd provide you with a quick list of the most useful points illustrated above: make your table markup as simple as possible, and keep things flexible, e.g. by using percentages, so the design is more responsive. use table-layout: fixed to create a more predictable table layout that allows you to easily set column widths by setting width on their headings (<th>). use bo...
...o layer styles on top of one another if required. use zebra striping to make alternative rows easier to read. use text-align to line up your <th> and <td> text, to make things neater and easier to follow. test your skills! we have covered a lot in this article, but can you remember the most important information? you can find some further tests to verify that you've retained this information before you move on — see test your skills: tables. summary with styling tables now behind us, we need something else to occupy our time. the next article explores debugging css — how to solve problems such as layouts not looking like they should, or properties not applying when you think they should. this includes information on using browser devtools to find solutions to your problems. previ...
The box model - Learn web development
g: border-box; } if you want all of your elements to use the alternative box model, and this is a common choice among developers, set the box-sizing property on the <html> element, then set all other elements to inherit that value, as seen in the snippet below. if you want to understand the thinking behind this, see the css tricks article on box-sizing. html { box-sizing: border-box; } *, *::before, *::after { box-sizing: inherit; } note: an interesting bit of history — internet explorer used to default to the alternative box model, with no mechanism available to switch. playing with box models in the below example, you can see two boxes. both have a class of .box, which gives them the same width, height, margin, border, and padding. the only difference is that the second box has b...
...use the <a> is an inline element. add display: inline-block to the rule with the .links-list a selector, and you will see how it fixes this issue by causing the padding to be respected by other elements. test your skills! we have covered a lot in this article, but can you remember the most important information? you can find some further tests to verify that you've retained this information before you move on — see test your skills: the box model. summary that's most of what you need to understand about the box model. you may want to return to this lesson in the future if you ever find yourself confused about how big boxes are in your layout. in the next lesson, we will take a look at how backgrounds and borders can be used to make your plain boxes look more interesting. previous...
Floats - Learn web development
u can follow along by creating a new index.html file on your computer, filling it with a simple html template, and inserting the below code into it at the appropriate places. at the bottom of the section, you can see a live example of what the final code should look like. first, we'll start off with some simple html — add the following to your html body, removing anything that was inside there before: <h1>simple float example</h1> <div class="box">float</div> <p>lorem ipsum dolor sit amet, consectetur adipiscing elit. nulla luctus aliquam dolor, eu lacinia lorem placerat vulputate. duis felis orci, pulvinar id metus ut, rutrum luctus orci. cras porttitor imperdiet nunc, at ultricies tellus laoreet sit amet. </p> <p>sed auctor cursus massa at porta. integer ligula ipsum, tristique sit amet...
... summary you now know all there is to know about floats in modern web development. see the article on legacy layout methods for information on how they used to be used, which may be useful if you find yourself working on older projects. previous overview: css layout next in this module introduction to css layout normal flow flexbox gr...
Positioning - Learn web development
example set up for future sections, first add a class of positioned to the second <p> in the html: <p class="positioned"> ... </p> now add the following rule to the bottom of your css: .positioned { position: static; background: yellow; } if you now save and refresh, you'll see no difference at all, except for the updated background color of the 2nd paragraph. this is fine — as we said before, static positioning is the default behavior! note: you can see the example at this point live at 1_static-positioning.html (see source code). relative positioning relative positioning is the first position type we'll take a look at. this is very similar to static positioning, except that once the positioned element has taken its place in the normal layout flow, you can then modify its final ...
...elative to the nearest ancestor with a "scrolling mechanism", which is determined by its ascendants' position property. note: you can see this example live at 7_sticky-positioning.html (see source code). test your skills! you've reached the end of this article, but can you remember the most important information? you can find some further tests to verify that you've retained this information before you move on — see test your skills: positioning. summary i'm sure you had fun playing with basic positioning; while it is not a method you would use for entire layouts, as you can see there are many tasks it is suited for. previous overview: css layout next ...
What is CSS? - Learn web development
ically readable even if no explicit styling is specified by the author of the page. however, the web would be a boring place if all websites looked like that. using css you can control exactly how html elements look in the browser, presenting your markup using whatever design you like. for more on browser/default styles, check out the following video: what is css for? as we have mentioned before, css is a language for specifying how documents are presented to users — how they are styled, laid out, etc. a document is usually a text file structured using a markup language — html is the most common markup language, but you may also come across other markup languages such as svg or xml. presenting a document to a user means converting it into a form usable by your audience. browsers, l...
...he 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 value pairs. each pair specifies a property of the element(s) we are selecting, then a value that we'd like to give the property. before the colon, we have the property, and after the colon, the value. css properties have different allowable values, depending on which property is being specified. in our example, we have the color property, which can take various color values. we also have the font-size property. this property can take various size units as a value. a css stylesheet will contain many such rules, written one after ...
Styling lists - Learn web development
c properties. there are three properties you should 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. list-style-image: allows you to use a custom image for the bullet, rather than a simple square or circle. bullet styles as mentioned above, the list-style-type property allows you to set what type of bullet to use for the bullet points. in our example, we've set the ordered list to use uppercase roman numerals, with: ol { list-style-type: upper-roman; } this gives ...
...let to use for the bullet points. in our example, we've set the ordered list to use uppercase roman numerals, with: ol { list-style-type: upper-roman; } this gives us the following look: you can find a lot more options by checking out the list-style-type reference page. bullet position the list-style-position property sets whether the bullets appear inside the list items, or outside them before the start of each item. the default value is outside, which causes the bullets to sit outside the list items, as seen above. if you set the value to inside, the bullets will sit inside the lines: ol { list-style-type: upper-roman; list-style-position: inside; } using a custom bullet image the list-style-image property allows you to use a custom image for your bullet. the syntax is prett...
Web fonts - Learn web development
ent usage contexts. a stylesheet.css file, which contains the generated @font-face code you'll need. to implement these fonts in your demo, follow these steps: rename the unzipped directory to something easy and simple, like fonts. open up the stylesheet.css file and copy both the @font-face blocks contained inside into your web-font-start.css file — you need to put them at the very top, before any of your css, as the fonts need to be imported before you can use them on your site. each of the url() functions points to a font file that we want to import into our css — we need to make sure the paths to the files are correct, so add fonts/ to the start of each path (adjust as necessary). now you can use these fonts in your font stacks, just like any web safe or default system font. for...
...nd choose a couple of fonts you like. to select a font family, press the ⊕ button alongside it. when you've chosen the font families, press the [number] families selected bar at the bottom of the page. in the resulting screen, you first need to copy the line of html code shown and paste it into the head of your html file. put it above the existing <link> element, so that the font is imported before you try to use it in your css. you then need to copy the css declarations listed into your css as appropriate, to apply the custom fonts to your html. note: you can find a completed version at google-font.html and google-font.css, if you need to check your work against ours (see it live). @font-face in more detail let's explore that @font-face syntax generated for you by fontsquirrel. this...
How do I start to design my website? - Learn web development
project, many people focus on the technical 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. so when you get an idea and want to turn it into a website, there are a few questions you should answer before anything else: what exactly do i want to accomplish? how will a website help me reach my goals? what needs to be done, and in what order, to reach my goals? all of this is called project ideation and is a necessary first step to reach your goal, whether you are a beginner or an experienced developer. active learning there is no active learning available yet. deeper dive a project never...
...yet. deeper dive a project never starts with the technical side. musicians will never make any music unless they first have an idea of what they want to play—and the same is true for painters, writers, and web developers. technique comes second. technique is obviously critical. musicians must master their instrument. but good musicians can never produce good music without an idea. therefore, before 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...
How do I use GitHub Pages? - Learn web development
it's simple and easy. once you've signed up, log in to github.com with your username and password. preparing your code for upload you can store any code you like in a github repository, but to use the github pages feature to full effect, your code should be structured as a typical website, e.g. with the primary entry point being an html file called index.html. the other thing you need to do before moving on is to initialise your code directory as a git repository. 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 li...
...r example, provided the home page is called index.html — it goes to this entry point by default. if your site's entry point is called something else, for example mypage.html, you'll need to go to https://xxxxxx/mypage.html. further github knowledge if you want to make more changes to your test site and upload those to github, you simply need to make the change to your files just like you did before. then, you need to enter the following commands (pressing enter after each one) to push those changes to github: git add --all git commit -m 'another commit' git push you can replace another commit with a more suitable message to describe what change you just made. we have barely scratched the surface of git. to learn more, check out our git and github page. ...
What is a URL? - Learn web development
e early days of the web, a path like this represented a physical file location on the web server. nowadays, it is mostly an abstraction handled by web servers without any physical reality. ?key1=value1&key2=value2 are extra parameters provided to the web server. those parameters are a list of key/value pairs separated with the & symbol. the web server can use those parameters to do extra stuff before returning the resource. each web server has its own rules regarding parameters, and the only reliable way to know if a specific web server is handling parameters is by asking the web server owner. #somewhereinthedocument is an anchor to another part of the resource itself. an anchor represents a sort of "bookmark" inside the resource, giving the browser the directions to show the content locat...
...between an absolute url and a relative url by looking only at the path part of the url. if the path part of the url starts with the "/" character, the browser will fetch that resource from the top root of the server, without reference to the context given by the current document. let's look at some examples to make this clearer. examples of absolute urls full url (the same as the one we used before) https://developer.mozilla.org/docs/learn implicit protocol //developer.mozilla.org/docs/learn in this case, the browser will call that url with the same protocol as the one used to load the document hosting 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...
What is a Domain Name? - Learn web development
component) the labels are what follow the tld. a label is a case-insensitive character sequence anywhere from one to sixty-three characters in length, containing only the letters a through z, digits 0 through 9, and the - character (which may not be the first or last character in the label). a, 97, and hello-strange-person-16-how-are-you are all examples of valid labels. the label located right before the tld is also called a secondary level domain (sld). a domain name can have many labels (or components). it is not mandatory nor necessary to have 3 labels to form a domain name. for instance, www.inf.ed.ac.uk is a valid domain name. for any domain you control (e.g. mozilla.org), you can create "subdomains" with different content located at each, like developer.mozilla.org, iot.mozilla.org, or...
... these servers refer to a few special servers called “authoritative name servers” or “top-level dns servers.” — these are like the boss servers that manage the system. whenever your registrar creates or updates any information for a given domain, the information must be refreshed in every dns database. each dns server that knows about a given domain stores the information for some time before it is automatically invalidated and then refreshed (the dns server queries an authoritative server and fetches the updated information from it). thus, it takes some time for dns servers that know about this domain name to get the up-to-date information. how does a dns request work? as we already saw, when you want to display a webpage in your browser it's easier to type a domain name than an ip...
The HTML5 input types - Learn web development
te: you can find examples of the basic text input types at basic input examples (see the source code also). this is another good reason for using these newer input types — improving the user experience for users of these devices. client-side validation as you can see above, email, along with other newer input types, provides built-in client-side error validation — performed by the browser before the data gets sent to the server. it is a helpful aid to guide users to fill out a form accurately, and it can save time — it is useful to know that your data is not correct immediately, rather than having to wait for a round trip to the server. but it should not be considered an exhaustive security measure! your apps should always perform security checks on any form-submitted data on the serv...
...os provides an example: and here is a live example for you to try out: the value returned is always a lowercase 6-value hexidecimal color. note: color inputs are not supported in internet explorer. test your skills! you've reached the end of this article, but can you remember the most important information? you can find some further tests to verify that you've retained this information before you move on — see test your skills: html5 controls. summary that brings us to the end of our tour of the html5 form input types. there are a few other control types that cannot be easily grouped together due to their very specific behaviors, but which are still essential to know about. we cover those in the next article. previous overview: forms next in this module your first for...
Other form controls - Learn web development
the browser usually sets them visually apart from the options (i.e. by being bolded and at a different nesting level) so they are less likely to be confused for actual options. if an <option> element has an explicit value attribute set on it, that value is sent when the form is submitted with that option selected. if the value attribute is omitted, as with the e...
... don't support the element and for assistive technologies to vocalize it. support for <progress> and <meter> is fairly good — there is no support in internet explorer, but other browsers support it well. test your skills! you've reached the end of this article, but can you remember the most important information? you can find some further tests to verify that you've retained this information before you move on — see test your skills: other controls. summary as you'll have seen in the last few articles, there are a lot of different types of available form element. you don't need to remember all of these details at once, and can return to these articles as often as you like to check up on details. now that you have a grasp of the html behind the different available form controls, we'll t...
Your first form - Learn web development
ne text fields, dropdown boxes, buttons, checkboxes, or radio buttons, and are mostly created using the <input> element, although there are some other elements to learn about too. form controls can also be programmed to enforce specific formats or values to be entered (form validation), and paired with text labels that describe their purpose to both sighted and blind users. designing your form before starting to code, it's always better to step back and take the time to think about your form. designing a quick mockup will help you to define the right set of data you want to ask your user to enter. from a user experience (ux) point of view, it's important 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 ...
.... our form will contain three text fields and one button. we are asking the user for their name, their e-mail and the message they want to send. hitting the button will send their data to a web server. active learning: implementing our form html ok, let's have a go at creating the html for our form. we will use the following html elements: <form>, <label>, <input>, <textarea>, and <button>. before you go any further, make a local copy of our simple html template — you'll enter your form html into here. the <form> element all forms start with a <form> element, like this: <form action="/my-handling-form-page" method="post"> </form> this element formally defines a form. it's a container element like a <section> or <footer> element, but specifically for containing forms; it also support...
Web forms — Working with user data - Learn web development
ntial. in the articles listed below, we'll cover all the essential aspects of web forms including marking up their html structure, styling form controls, validating form data, and submitting data to the server. looking to become a front-end web developer? we have put together a course that includes all the essential information you need to work towards your goal. get started prerequisites before starting this module, you should at least work through our introduction to html. at this point you should find the introductory guides 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 re...
...his point you should find the introductory guides easy to understand, and also be able to make use of our basic native form controls guide. mastering forms however requires more than just html knowledge — you also need to learn some specific techniques to style form controls, and some scripting knowledge is required to handle things like validation and creating custom form controls. therefore, before you look at the other sections listed below we'd recommend that you go away and learn some css and javascript first. the above text is a good indicator as to why we've put web forms into its own standalone module, rather than trying to mix bits of it into the html, css, and javascript topic areas — form elements are more complex than most other html elements, and they also require a close marr...
HTML basics - Learn web development
lement a bit further. the main parts of our element are as follows: the opening tag: this consists of the name of the element (in this case, p), wrapped in opening and closing angle brackets. this states where the element begins or starts to take effect — in this case where the paragraph begins. the closing tag: this is the same as the opening tag, except that it includes a forward slash before the element name. this states where 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...
...to describe the page when you bookmark/favourite it. <body></body> — the <body> element. this contains all the content that you want to show to web users when they visit your page, whether that's text, images, videos, games, playable audio tracks or whatever else. images let's turn our attention to the <img> element again: <img src="images/firefox-icon.png" alt="my test image"> as we said before, it embeds an image into our page in the position it appears. it does this via the src (source) attribute, which contains the path to our image file. we have also included an alt (alternative) attribute. in this attribute, you specify descriptive text for users who cannot see the image, possibly because of the following reasons: they are visually impaired. users with significant visual impair...
How the Web works - Learn web development
clients and servers computers connected to the web are called clients and servers. ...
...ta should travel across the internet. this is like the transport mechanisms that let you place an order, go to the shop, and buy your goods. in our example, this is like a car or a bike (or however else you might get around). dns: domain name servers are like an address book for websites. when you type a web address in your browser, the browser looks at the dns to find the website's real address before it can retrieve the website. the browser needs to find out which server the website lives on, so it can send http messages to the right place (see below). this is like looking up the address of the shop so you can access it. http: hypertext transfer protocol is an application protocol that defines a language for clients and servers to speak to each other. this is like the language you use to ord...
JavaScript basics - Learn web development
world! is the standard for introductory programming examples.) important: if you haven't been following along with the rest of our course, download this example code and use it as a starting point. go to your test site and create a new folder named scripts. within the scripts folder, create a new file called main.js, and save it. in your index.html file, enter this code on a new line, just before the closing </body> tag: <script src="scripts/main.js"></script> this is doing the same job as the <link> element for css. it applies the javascript to the page, so it can have an effect on the html (along with the css, and anything else on the page). add this code to the main.js file: const myheading = document.queryselector('h1'); myheading.textcontent = 'hello world!'; make sure the...
...onalized welcome message next, let's change the page title to a personalized welcome message when the user first visits the site. this welcome message will persist. should the user leave the site and return later, we will save the message using the web storage api. we will also include an option to change the user, and therefore, the welcome message. in index.html, add the following line just before the <script> element: <button>change user</button> in main.js, place the following code at the bottom of the file, exactly as it is written. this takes references to the new button and the heading, storing each inside variables: let mybutton = document.queryselector('button'); let myheading = document.queryselector('h1'); add the function below to set the personalized greeting. this wo...
The web and web standards - Learn web development
to buy to continue making web sites, or worse still, just deciding they aren't interested any more and just turning it off. this allows the web to remain a freely-available public resource. don't break the web another phrase you'll hear around open web standards is "don't break the web" — the idea is that any new web technology that is introduced should be backwards compatible with what went before it (i.e. old web sites will still continue to work), and forwards compatible (future technologies in turn will be compatible with what we currently have). as you go through the learning material presented here, you'll start to learn how this is made possible with some very clever design and implementation work. being a web developer is good the web industry is a very attractive market to enter ...
...at they are smaller and therefore download from the server more quickly. server-side languages and frameworks html, css, and javascript are front-end (or client-side) languages, which means they are run by the browser to produce a website front-end that your users can use. there are another class of languages called back-end (or server-side) languages, meaning that they are run on the server before the result is then sent to the browser to be displayed. a typical use for a server-side language is to get some data out of a database and generate some html to contain the data, before then sending the html over to the browser to display it to the user. example server-side languages include asp.net, python, php, and nodejs. web best practices we have briefly talked about the technologies that...
What will your website look like? - Learn web development
what should your website actually do? a website can do basically anything, but, for your first try, you should keep things simple. we'll start by creating a simple webpage with a heading, an image, and a few paragraphs. ...
...what should your website actually do? a website can do basically anything, but, for your first try, you should keep things simple. we'll start by creating a simple webpage with a heading, an image, and a few paragraphs. ...
Getting started with HTML - Learn web development
s example, p for paragraph), wrapped in opening and closing angle brackets. this opening tag marks where the element begins or starts to take effect. in this example, it precedes the start of the paragraph text. the content: this is the content of the element. in this example, it is the paragraph text. the closing tag: this is the same as the opening tag, except that it includes a forward slash before the element name. this marks where the element ends. failing to include a closing tag is a common beginner error that can produce peculiar results. the element is the opening tag, followed by content, followed by the closing tag. active learning: creating your first html element edit the line below in the input area by wrapping it with the tags <em> and </em>. to open the element, put the ope...
...ted to state that our cat is very grumpy, we could wrap the word very in a <strong> element, which means that the word is to have strong(er) text formatting: <p>my cat is <strong>very</strong> grumpy.</p> there is a right and wrong way to do nesting. in the example above, we opened the p element first, then opened the strong element. for proper nesting, we should close the strong element first, before closing the p. the following is an example of the wrong way to do nesting: <p>my cat is <strong>very grumpy.</p></strong> the tags have to open and close in a way that they are inside or outside one another. with the kind of overlap in the example above, the browser has to guess at your intent. this kind of guessing can result in unexpected results. block versus inline elements there are two...
Mozilla splash page - Learn web development
objective: to test knowledge around embedding images and video in web pages, frames, and html responsive image techniques. ...
...ts of index.html in a file called index.html on your local drive, in a new directory. then save pattern.png in the same directory (right click on the image to get an option to save it.) access the different images in the originals directory and save them in the same way; you'll want to save them in a different directory for now, as you'll need to manipulate (some of) them using a graphics editor before they're ready to be used. alternatively, you could use an online tool such as glitch to create your example. this would also be useful if you want to get it assessed, or ask for help — see the assessment or further help section at the bottom of this page. note: the example html file contains quite a lot of css, to style the page. you don't need to touch the css, just the html inside the <bod...
Structuring the web with HTML - Learn web development
sed to specify whether your web content should be recognized as a paragraph, list, heading, link, image, multimedia player, form, or one of many other available elements or even a new element that you define. looking to become a front-end web developer? we have put together a course that includes all the essential information you need to work towards your goal. get started prerequisites before starting this topic, you should have at least basic familiarity with using computers and using the web passively (i.e. just looking at it, consuming the content). you should have a basic work environment set up as detailed in installing basic software, and understand how to create and manage files, as detailed in dealing with files — both are parts of our getting started with the web complete b...
...d using the web passively (i.e. just looking at it, consuming the content). you should have a basic work environment set up as detailed in installing basic software, and understand how to create and manage files, as detailed in dealing with files — both are parts of our getting started with the web complete beginner's module. it is recommended that you work through getting started with the web before attempting this topic, however, it isn't absolutely necessary; much of what is covered in the html basics article is also covered in our introduction to html module, albeit in a lot more detail. after learning html, you can then move on to learning about more advanced topics such as: css, and how to use it to style html (for example alter your text size and fonts used, add borders and drop sh...
Functions — reusable blocks of code - Learn web development
conclusion this article has explored the fundamental concepts behind functions, paving the way for the next one in which we get practical and take you through the steps to building up your own custom function. ...
...function3(value) { console.log(value); } test your skills! you've reached the end of this article, but can you remember the most important information? you can find some further tests to verify that you've retained this information before you move on — see test your skills: functions. these tests require skills that are covered in the next two articles, so you might want to read those first before trying it. conclusion this article has explored the fundamental concepts behind functions, paving the way for the next one in which we get practical and take you through the steps to building up your own custom function. ...
Function return values - Learn web development
code continues. so when you execute the following: ctx.arc(random(width), random(height), random(50), 0, 2 * math.pi); if the three random() calls returned the values 500, 200, and 35, respectively, the line would actually be run as if it were this: ctx.arc(500, 200, 35, 0, 2 * math.pi); the function calls on the line are run first, and their return values substituted for the function calls, before the line itself is then executed. active learning: our own return value function let's have a go at writing our own functions featuring return values. first of all, make a local copy of the function-library.html file from github. this is a simple html page containing a text <input> field and a paragraph. there's also a <script> element, in which we have stored a reference to both html elemen...
... and over again. it is a good idea to create your own library of utility functions to do these sorts of things. you can copy them over to new code, or even just apply it to html pages wherever you need it. test your skills! you've reached the end of this article, but can you remember the most important information? you can find some further tests to verify that you've retained this information before you move on — see test your skills: functions. conclusion so there we have it — functions are fun, very useful, and although there's a lot to talk about in regards to their syntax and functionality, they are fairly understandable. if there is anything you didn't understand, feel free to read through the article again, or contact us to ask for help. ...
Making decisions in your code — conditionals - Learn web development
the ternary or conditional operator is a small bit of syntax that tests a condition and returns one value/expression if it is true, and another if it is false — this can be useful in some situations, and can take up a lot less code than an if...else block if you simply have two choices that are chosen between via a true/false condition. the pseudocode look...
... conclusion and that's all you really need to know about conditional structures in javascript right now! if there is anything you didn't understand, feel free to read through the article again, or contact us to ask for help. ...
Fetching data from the server - Learn web development
small chunks of data (such as html, xml, json, or plain text) and display them only when needed, helping to solve the problem described above. this is achieved by using apis like xmlhttprequest or — more recently — the fetch api. these technologies allow web pages to directly handle making http requests for specific resources available on a server and formatting the resulting data as needed before it is displayed. note: in the early days, this general technique was known as asynchronous javascript and xml (ajax), because it tended to use xmlhttprequest to request xml data. this is normally not the case these days (you'd be more likely to use xmlhttprequest or fetch to request json), but the result is still the same, and the term "ajax" is still often used to describe the technique. t...
...sary here — xhr returns text by default — but it is a good idea to get into the habit of setting this in case you want to fetch other types of data in the future. add this next: request.responsetype = 'text'; fetching a resource from the network is an asynchronous operation, meaning that you have to wait for that operation to complete (e.g., the resource is returned from the network) before you can do anything with that response, otherwise, an error will be thrown. xhr allows you to handle this using its onload event handler — this is run when the load event fires (when the response has returned). when this has occurred, the response data will be available in the response property of the xhr request object. add the following below your last addition. you'll see that inside the ...
Manipulating documents - Learn web development
in the tree, but it is a descendant of body. parent node: a node which has another node inside it. for example, body is the parent node of section in the above example. sibling nodes: nodes that sit on the same level in the dom tree. for example, img and p are siblings in the above example. text node: a node containing a text string. it is useful to familiarize yourself with this terminology before working with the dom, as a number of the code terms you'll come across make use of them. you may have also come across them if you have studied css (e.g. descendant selector, child selector). active learning: basic dom manipulation to start learning about dom manipulation, let's begin with a practical example. take a local copy of the dom-example.html page and the image that goes along with ...
...w we can create new elements. going back to the current example, let's start by grabbing a reference to our <section> element — add the following code at the bottom of your existing script (do the same with the other lines too): const sect = document.queryselector('section'); now let's create a new paragraph using document.createelement() and give it some text content in the same way as before: const para = document.createelement('p'); para.textcontent = 'we hope you enjoyed the ride.'; you can now append the new paragraph at the end of the section using node.appendchild(): sect.appendchild(para); finally for this part, let's add a text node to the paragraph the link sits inside, to round off the sentence nicely. first we will create the text node using document.createtextnod...
Third-party APIs - Learn web development
king something like this: https://api.nytimes.com/svc/search/v2/articlesearch.json?api-key=your-api-key-here&page=0&q=cats &fq=document_type:("article")&begin_date=20170301&end_date=20170312 note: you can find more details of what url parameters can be included at the nytimes developer docs. note: the example has rudimentary form data validation — the search term field has to be filled in before the form can be submitted (achieved using the required attribute), and the date fields have pattern attributes specified, which means they won't submit unless their values consist of 8 numbers (pattern="[0-9]{8}"). see form data validation for more details on how these work. requesting data from the api now we've constructed our url, let's make a request to it. we'll do this using the fetch ap...
... if(pagenumber > 0) { pagenumber--; } else { return; } fetchresults(e); }; the first function is simple — we increment the pagenumber variable, then run the fetchresults() function again to display the next page's results. the second function works nearly exactly the same way in reverse, but we also have to take the extra step of checking that pagenumber is not already zero before decrementing it — if the fetch request runs with a minus page url parameter, it could cause errors. if the pagenumber is already 0, we simply return out of the function, to avoid wasting processing power (if we are already at the first page, we don't need to load the same results again). note: you can find our finished nytimes api example code on github (also see it running live here). y...
A first splash into JavaScript - Learn web development
let's imagine your boss has given you the following brief for creating this game: i want you to create a simple guess the number type game. it should choose a random number between 1 and 100, then challenge the player to guess the number in 10 turns. after each turn the player should be told if they are right or wrong, and if they are wrong, whether the guess was too low or too hi...
...ent.queryselectorall('.resultparas p'); for (let i = 0 ; i < resetparas.length ; i++) { resetparas[i].textcontent = ''; } this code creates a variable containing a list of all the paragraphs inside <div class="resultparas"> using the queryselectorall() method, then it loops through each one, removing the text content of each. a small discussion on objects let's add one more final improvement before we get to this discussion. add the following line just below the let resetbutton; line near the top of your javascript, then save your file: guessfield.focus(); this line uses the focus() method to automatically put the text cursor into the <input> text field as soon as the page loads, meaning that the user can start typing their first guess right away, without having to click the form field fi...
Working with JSON - Learn web development
accessing the javascript object, because we set the xhr request to convert the json response directly into a javascript object using: request.responsetype = 'json'; but sometimes we aren't so lucky — sometimes we receive a raw json string, and we need to convert it to an object ourselves. and when we want to send a javascript object across the network, we need to convert it to json (a string) before sending. luckily, these two problems are so common in web development that a built-in json object is available in browsers, which contains the following two methods: parse(): accepts a json string as a parameter, and returns the corresponding javascript object. stringify(): accepts an object as a parameter, and returns the equivalent json string form. you can see the first one in action in ...
...ring here we're creating a javascript object, then checking what it contains, then converting it to a json string using stringify() — saving the return value in a new variable — then checking it again. test your skills! you've reached the end of this article, but can you remember the most important information? you can find some further tests to verify that you've retained this information before you move on — see test your skills: json. summary in this article, we've given you a simple guide to using json in your programs, including how to create and parse json, and how to access data locked inside it. in the next article, we'll begin looking at object-oriented javascript. ...
Object building practice - Learn web development
greater than the height of the canvas (the ball is going off the bottom edge). if the y coordinate is smaller than 0 (the ball is going off the top edge). in each case, we include the size of the ball in the calculation because the x/y coordinates are in the center of the ball, but we want the edge of the ball to bounce off the perimeter — we don't want the ball to go halfway off the screen before it starts to bounce back. the last two lines add the velx value to the x coordinate, and the vely value to the y coordinate — the ball is in effect moved each time this method is called. this will do for now; let's get on with some animation! animating the ball now let's make this fun. we are now going to start adding balls to the canvas, and animating them. first, we need to create some...
...basis for most games and other such programs. our loop() function does the following: sets the canvas fill color to semi-transparent black, then draws a rectangle of the color across the whole width and height of the canvas, using fillrect() (the four parameters provide a start coordinate, and a width and height for the rectangle drawn). this serves to cover up the previous frame's drawing before the next one is drawn. if you don't do this, you'll just see long snakes worming their way around the canvas instead of balls moving! the color of the fill is set to semi-transparent, rgba(0,0,0,0.25), to allow the previous few frames to shine through slightly, producing the little trails behind the balls as they move. if you changed 0.25 to 1, you won't see them at all any more. try varying this...
Object prototypes - Learn web development
son1's prototype object has a valueof() method available on it. it doesn't, then the browser checks person1's prototype object's prototype object, and it has. so the method is called, and all is good! note: we want to reiterate that the methods and properties are not copied from one object to another in the prototype chain. they are accessed by walking up the chain as described above. note: before ecmascript 2015, there wasn't officially a way to access an object's prototype directly — the "links" between the items in the chain are defined in an internal property, referred to as [[prototype]] in the specification for the javascript language (see ecmascript). most modern browsers, however, do offer property available called __proto__ (that's 2 underscores either side), which contains the...
...efinition test.prototype.x = function() { ... }; // second method definition test.prototype.y = function() { ... }; // etc. this pattern can be seen in action in piotr zalewa's school plan app example. test your skills! you've reached the end of this article, but can you remember the most important information? you can find some further tests to verify that you've retained this information before you move on — see test your skills: object-oriented javascript. note that this set of tests relies on some of the knowledge taught in the next article, so you might want to read that first before you try them. summary this article has covered javascript object prototypes, including how prototype object chains allow objects to inherit features from one another, the prototype property and how ...
Introducing JavaScript objects - Learn web development
and if you want to go further with your knowledge of the language, therefore we've provided this module to help you. here we teach object theory and syntax in detail, then look at how to create your own objects. 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. ...
...n look at how to create your own objects. looking to become a front-end web developer? we have put together a course that includes all the essential information you need to work towards your goal. get started prerequisites before starting this module, you should have some familiarity with html and css. you are advised to work through the introduction to html and introduction to css modules before starting on javascript. you should also have some familiarity with javascript basics before looking at javascript objects in detail. before attempting this module, work through javascript first steps and javascript building blocks. note: if you are working on a computer/tablet/other devices where you don't have the ability to create your own files, you could try out (most of) the code examples...
Multimedia: Images - Learn web development
, with the adoption of priority hints, you can control the priority further by adding an importance attribute to your image tags. an example use case for priority hints on images are carousels where the first image is a higher priority than the subsequent images. ...
... conclusion in this section we took a look at image optimization. you now have a general understanding of how to optimize half of the average web sites average bandwidth total. this is just one of the types of media consuming users bandwidth and slowing down page load. ...
Ember app structure and componentization - Learn web development
to ensure that our app continues to work over time as we upgrade, add features, refactor, etc. testing is outside the scope of this tutorial, although generally testing should be implemented as you develop, rather than after, otherwise it tends to be forgotten about. if you're curious about testing, or why you would want to have automated tests, check out the official ember tutorial on testing. before we start adding any component code, let’s create the scaffolding for the other components. enter the following lines into your terminal, one by one: ember generate component todo-list ember generate component todo ember generate component footer you’ll now see the following inside your todomvc/app/components directory: now that we have all of our component structure files, we can cut and...
... notice how the todo items both say "buy movie tickets" — this is because the same component is being invoked twice, and the todo text is hardcoded into it. we'll look at showing different todo items in the next article! summary great! everything looks as it should. we have successfully refactored our html into components! in the next article we'll start looking into adding...
Introduction to client-side frameworks - Learn web development
nal element would look like. that might be a useful idea for something as simple as our to-do list application, but it's not maintainable for large applications that manage thousands of records of data, and could render just as many unique elements in a user interface. other things frameworks give us let's look at some of the other advantages conferred upon us by frameworks. as we've alluded to before, the advantages of frameworks are achievable in vanilla javascript, but using a framework takes away all of the cognitive load of having to solve these problems yourself. tooling because each of the frameworks in this module have a large, active community, each framework's ecosystem provides tooling that improves the developer experience. these tools make it easy to add things like testing (to ...
... easy, but they are not a silver bullet that will solve all problems. this section talks about some of the things you should consider when using frameworks. bear in mind that you might not need a framework at all — beware that you don't end up using a framework just for the sake of it. familiarity with the tool just like vanilla javascript, frameworks take time to learn and have their quirks. before you decide to use a framework for a project, be sure you have time to learn enough of its features for it to be useful to you rather than it working against you, and be sure that your teammates are comfortable with it as well. overengineering if your web development project is a personal portfolio with a few pages, and those pages have little or no interactive capability, a framework (and all o...
Getting started with Svelte - Learn web development
more mature frameworks, and there are also less job opportunities. but it's advantages should be enough to make you interested to explore it. note: recently svelte has added official typescript support, one of its most requested features. we'll look at it later on in this tutorial series. we encourage you to go through the svelte tutorial for a really quick introduction to the basic concepts, before returning to this tutorial series to learn how to build something slightly more in-depth. it should take you about 30 minutes to complete. use cases svelte can be used to develop small pieces of an interface or whole applications. you can either start from scratch letting svelte drive your ui or you can incrementally integrate it into an existing application. nevertheless, svelte is particular...
...tart your app in development mode. repl to code along with us using the repl, start at https://svelte.dev/repl/fc68b4f059d34b9c84fa042d1cce586c?version=3.23.2 summary this brings us to the end of our initial look at svelte, including how to install it locally, create a starter app, and how the basics work. in the next article we'll start building our first proper application — a todo list. before we do that, however, let's recap some of the things we’ve learned. in svelte: we define the script, style and markup of each component in a single .svelte file. component props are declared with the export keyword. svelte components can be used just by importing the corresponding .svelte file. components styles are scoped, keeping them from clashing with each other. in the markup sectio...
Working with Svelte stores - Learn web development
ll do later, the reactive $store syntax will also apply to your stores. let's apply this to our alert component. update the <script> and markup sections of alert.svelte as follows: <script> import { alert } from '../stores.js' </script> {#if $alert} <div on:click={() => $alert = ''}> <p>{ $alert }</p> </div> {/if} check your app again and you'll see that this works just like before. that's much better! behind the scenes svelte has generated the code to declare the local variable $alert, subscribe to the alert store, update $alert whenever the store's content is modified, and unsubscribe when the component is unmounted. it will also generate the alert.set(...) statements whenever we assign a value to $alert. the end result of this nifty trick is that you can access glob...
...piler won't touch anything outside of svelte components. in that case you'll have to rely on the store.subscribe() and store.set() methods. improving our alert component it's a bit annoying having to click on the alert to get rid of it. it would be better if the notification just disappeared after a couple of seconds. lets see how to do that. we'll specify a prop with the milliseconds to wait before clearing the notification, and we'll define a timeout to remove the alert. we'll also take care of clearing the timeout when the alert component is unmounted to prevent memory leaks. update the <script> section of your alert.svelte component like so: <script> import { ondestroy } from 'svelte' import { alert } from '../stores.js' export let ms = 3000 let visible let timeout ...
Vue conditional rendering: editing existing todos - Learn web development
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 emits the new label via an item-edited event. when the "cancel" button is clicked, ...
...s 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 emits the new label via an item-edited event. when the "cancel" button is clicked, the component signals this by emitting an edit-cancelled event. modifying our todoitem component before we can add todoitemeditform to our app, we need to make a few modifications to our todoitem component. specifically, we need to add a variable to track if the item is being edited, and a button to toggle that variable. we’ll also add a delete button since deletion is closely related. update your todoitem’s template as shown below. <template> <div class="stack-small"> <div class="custo...
Creating our first Vue component - Learn web development
h key corresponding to the prop name. listing props as an object allows you to specify default values, mark props as required, perform basic object typing (specifically around javascript primitive types), and perform simple prop validation. note: prop validation only happens in development mode, so you can't strictly rely on it in production. additionally, prop validation functions are invoked before the component instance is created, so they do not have access to the component state (or other props). for this component, we’ll use the object registration method. go back to your todoitem.vue file. add a props property inside the export default {} object, which contains an empty object. inside this object, add two properties with the keys label and done. the label key's value should b...
...ow that content inside {{}} is displayed as text and not html. in this case, we’re printing the value of the label prop. your component’s template section should now look like this: <template> <div> <input type="checkbox" id="todo-item" checked="false" /> <label for="todo-item">{{label}}</label> </div> </template> go back to your browser and you'll see the todo item rendered as before, but without a label (oh no!). go to your browser's devtools and you’ll see a warning along these lines in the console: [vue warn]: missing required prop: "label" found in ---> <todoitem> at src/components/todoitem.vue <app> at src/app.vue <root> this is because we marked the label as a required prop, but we never gave the component that prop — we've defined where inside ...
Understanding client-side JavaScript frameworks - Learn web development
provide you with enough context and familiarity to start going into greater depth yourself. we want you to go forward and learn about frameworks in a pragmatic way that doesn't forget about web platform fundamental best practices such as accessibility. get started now, with "introduction to client-side frameworks" prerequisites you should really learn the basics of the core web languages first before attempting to move on to learning client-side frameworks — html, css, and especially javascript. your code will be richer and more professional as a result, and you'll be able to troubleshoot problems with more confidence if you understand the fundamental web platform features that the frameworks are building on top of. looking to become a front-end web developer? we have put together a cou...
...n react – an app that allows users to add, edit, and delete tasks they want to work on, and also mark tasks as complete without deleting them. this article will walk you through putting the basic app component structure and styling in place, ready for individual component definition and interactivity, which we'll add later. 3. componentizing our react app at this point, our app is a monolith. before we can make it do things, we need to break it apart into manageable, descriptive components. react doesn’t have any hard rules for what is and isn’t a component – that’s up to you! in this article, we will show you a sensible way to break our app up into components. 4. react interactivity: events and state with our component plan worked out, it's now time to start updating our app from ...
Strategies for carrying out testing - Learn web development
ersions of each), ios safari for iphone/ipad, android stock browser (last two versions) on phone/tablet, chrome and firefox for android (last two versions) on phone tablet. accessibility passing common tests. b grade: ie 8 and 9 for windows, opera mini. c grade: opera, other niche modern browsers. what are you going to test? when you've got a new addition to your codebase that needs testing, before you start testing you should write out a list of testing requirements that need to pass to be accepted. these requirements can be visual or functional — both combine to make a usable web site feature. consider the following example (see the source code, and also the example running live): test criteria for this feature could be written like so: a and b grade: button should be activatabl...
...get it worked out. there are also commercial tools available such as sauce labs, browser stack and lambdatest that do this kind of thing for you, without you having to worry about the setup, if you wish to invest some money in your testing. another alternative is to use no-code test automation tools such as endtest. we will look at how to use such tools later on in the module. user testing before we move on, we'll finish this article off by talking a bit about user testing — this can be a good option if you have a willing user group to test your new functionality on. bear in mind that this can be as lo-fi or as sophisticated as you like — your user group could be a group of friends, a group of colleagues, or a group of unpaid or paid volunteers, depending on whether you have any money...
Tools and testing - Learn web development
port. in most cases there are other tools available, old ones will go out of fashion, and new ones will no doubt appear. 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 you should really learn the basics of the core html, css, and javascript languages first before attempting to use many the tools detailed here. for example, you'll need to know the fundamentals of these languages before you start debugging problems in complex web code, making effective use of javascript frameworks, or writing tests and running them against your code using test runners. in addition, you should start with the first module in this topic, which gives a useful overview of the g...
...end web development, providing developers with tried and tested tools for building scalable, interactive web applications. many modern companies use frameworks as a standard part of their tooling, so many front-end development jobs now require framework experience. this module gives you some fundamental background knowledge about how client-side frameworks work and how they fit into your toolset, before moving on to tutorial series covering some of today's most popular ones. git and github all developers will use some kind of version control system (vcs), a tool to allow them to collaborate with other developers on a project without danger of them overwriting each other's work, and roll back to previous versions of the code base if a problem is discovered later on. the most popular vcs (at lea...
Accessibility API cross-reference
g text could trigger display of one or more predictions of the user's intended value for an input and specifies how predictions would be presented if they are made. n/a n/a aria-autocomplete the control cannot accept input at this time. indicates an element is being modified and that assistive technologies may want to wait until the modifications are complete before exposing them to the user. busy busy busy aria-busy indicates the current "checked" state of checkboxes, radio buttons, and other widgets. checked checked checked aria-checked checked (boolean attribute) defines the total number of columns in a table, grid, or treegrid. n/a n/a aria-colcount ...
...ean attribute) indicates whether the object is in an iconified or minimized state. ...
Theme concepts
ng images to the header area of the firefox browser; this is the area behind the menu bar, toolbars, address bar, search bar, and tab strip. these theme options can be implemented as static themes (although the theme images themselves may be animated) or as dynamic themes created in a browser extension. if you have a lightweight theme it will be converted to this new theme format automatically before lightweight themes are deprecated. you do not need to port your theme. however, please feel free to update your themes to use any of the new features described here. static themes static themes are specified using the same resources as a browser extension: a manifest.json file to define the theme components with those components stored in the same folder as the manifest.json file or a sub fold...
...ader theme, as in this code snippet from the same example: function settheme(theme) { if (currenttheme === theme) { // no point in changing the theme if it has already been set. return; } currenttheme = theme; browser.theme.update(themes[theme]); } learn more about dynamic themes and see an additional example in the following video: if you have not built a browser extension before, check out your first extension for a step-by-step guide. cross-browser compatibility there is currently limited compatibility between themes in the major browsers. opera takes an entirely different approach, and microsoft edge themes are not yet open to developers. there is good compatibility between firefox static themes and chrome themes, providing the ability to port a single header image ...
What to do and what not to do in Bugzilla
to get bugzilla privileges (as described below), please see this page. 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. include a link to your bugzilla activity page in the bug description. before you have canconfirm, you can still do good triaging by leaving comments with useful information on the bug that will help to confirm it. the same is true for editbugs: leave comments with the information you'd like to be able to edit into the bug, and that will help you get the editbugs permissions quickly. canconfirm privilege the canconfirm privilege allows you to confirm bugs and also to st...
...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 or someone who has been explicitly told by a module owner or module peer that they are able to do so for that module. before verifying fixed bugs, make sure that you can verify them on every hardware/os they were reported on. if that's impossible, try to cooperate with multiple people to verify the bug. there are no clear rules for verifying worksforme. in general you should make sure that the bug has been resolved for a few months and no complaints about the resolution have come up. note: because of how duplicate ...
Creating reftest-based unit tests
that the screen displays the correct output the next time it is repainted. invalidation tests check both that the internal state of the document has been updated correctly, and that the browser then correctly invalidates and repaints the appropriate parts of the screen. in order to test invalidation it is important that invalidation tests let the document completely finish loading and displaying before making the changes for which invalidation and repainting is to be tested. making the changes before the document has completely finished loading and painting would mean that the test may not actually test the browser's invalidation logic, since the changed parts of the document may end up displaying correctly purely due to a pending post-load paint. to write an invalidation reftest requires thre...
...to try and wait for the initial rendering to be done using a settimeout, but that would be unreliable, and just as bad, it can increase the time it takes to run a test many times over (which when you're running thousands of tests can really slow things down). the 'mozreftestinvalidate' event is designed to fire as soon after the initial rendering of the document is finished as possible, but never before. the reftest framework fires one mozreftestinvalidate event at the document root element for a reftest-wait test when it is safe to make changes that should test invalidation. the event bubbles up to the document and window so you can set listeners there too. references http://old.nabble.com/please-add-%22in-testsuite-%22-to-layout-bugs-when-resolving-them!-td7787412.html further documentati...
Debugging JavaScript
browser console instead. browser debugger (built-in) on firefox 19 or later, it's possible to use the built-in js debugger on the browser itself. go to about:config and set the following two prefs: devtools.chrome.enabled: true devtools.debugger.remote-enabled: true after you restart the browser, you can access the browser debugger through tools > web developer > browser toolbox. (note that before firefox 28, this was labeled "browser debugger" and only the debugger was available, not the whole toolbox.) note that you must accept the incoming connection : (you may disable the pop-up above with the devtools.debugger.prompt-connection set to false in about:config. this can be a security risk, especially if you also set the devtools.debugger.force-local preference to false.) then, the ...
...was available, not the whole toolbox.) note that you must accept the incoming connection : (you may disable the pop-up above with the devtools.debugger.prompt-connection set to false in about:config. this can be a security risk, especially if you also set the devtools.debugger.force-local preference to false.) then, the browser toolbox displays the available tools for debugging. (note that before firefox 28, only the script debugger was available.) the use of these tools are the same as the built-in tools. strict code checking if you set the pref javascript.options.strict to true, the javascript engine gives you more types of warnings on the error console, most of which hint at code bugs that are easy to oversee or even bad syntax. (the pref also warns on common javascript idioms th...
Debugging on Mac OS X
ity protection (sip) if debugging a production build is required, follow apple's documented steps for disabling system integrity protection (sip). note that disabling sip bypasses hardened runtime restrictions which can mask some bugs that only occur with hardened runtime so it is recommended to test fixes with sip enabled. disabling sip has system security implications that should be understood before taking this step. creating an xcode project if you try to create a new xcode project in an existing directory then xcode will delete its existing contents (xcode will warn you beforehand). to work around that, the steps below have you initialize the project outside the mozilla source tree, close the project, copy the .xcodeproj project "file" into the source tree, and then reopen the project t...
...ility to modify-rebuild-relaunch from inside xcode. these steps were last updated for xcode 10.3: open xcode, and create a new project with file > new project. select the "cross-platform" tab then under the "other" template group select the "empty" project type. the click next. name the project and click next. create/select a temporary directory to contain the project and then click create. before going any further, close the project (file > close project) and open finder. find the *.xcodejproj directory in the temporary directory, move it into your mozilla source tree, and then double-click on it to reopen it. in the left-hand pane in xcode you should see a tree item where the root item has the project name. if the temporary directory that you originally created the xcode project in is u...
HTTP logging
arting with firefox 52. this is the best and easiest way to do http logging. at any point during while your browser is running, you can turn logging on and off. this allows you to capture only the "interesting" part of the browser's behavior (i.e. your bug), which makes the http log much smaller and easier to analyze. launch the browser and get it into whatever state you need to be in just before your bug occurs. open a new tab and type in "about:networking" into the url bar. go to the "logging section" adjust the location of the log file if you don't like the default adjust the list of modules that you want to log: this list has the exact same format as the moz_log environment variable (see below). generally the default list is ok, unless a mozilla developer has told you to modify i...
... all the logs to be uploaded--ask the developer if you're not sure. pat yourself on the back--a job well done! thanks for helping us debug firefox. logging http activity by manually setting environment variables sometimes the about:networking approach won't work, for instance if your bug occurs during startup, or you're running on mobile, etc. in that case you can set environment variables *before* you launch firefox. note that this approach winds up logging the whole browser history, so files can get rather large (they compress well :) setting environment variables differs by operating system. don't let the scary-looking command line stuff frighten you off; 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 fin...
Simple SeaMonkey build
ild\start-msvc2013.bat. even if you're on 64-bit windows, do not use the files ending in -x64.bat. by default you will arrive in your windows user home directory which is likely to contain spaces in its path (e.g. c:\users\myaccount). this can lead to problems later in the building stage. to avoid that, create a directory without spaces in its path (e.g. mkdir /c/mozilla-src) and switch to it before building (cd /c/mozilla-src). problems? see windows build prerequisites. building seamonkey building seamonkey requires at least 2 gb of disk space and 256 mb of available ram. # get the source # for aurora, use https://hg.mozilla.org/releases/comm-aurora/ and comm-aurora instead # for beta, use https://hg.mozilla.org/releases/comm-beta/ and comm-beta instead # for release, u...
... but it should work if you --disable-mailnews. on windows, the above commands will create the comm-central directory in %userprofile% which may be some subfolder of c:\documents and settings\ on systems upgraded from xp or below. the space in this directory name, or in your user name if it contains one, will cause the configure script to break. to (possibly) fix this, cd to a dir without spaces before doing the "hg clone" command above. running seamonkey the seamonkey executable can be found in obj-sm-release/dist/bin/ (used to be obj-sm-release/mozilla/dist/bin/) on windows and linux and in obj-sm-release/dist/seamonkey.app/contents/macos/ on mac. how to build again later in your comm-central directory, run these commands: # get the latest source python client.py checkout then just re...
Simple Sunbird build
prerequisites. building sunbird building sunbird requires at least 2.5 gb of disk space, 500 mb of ram, and lots of available swap space. on windows, if you open the command prompt you are usually in your user profile folder which often contains spaces ( c:\documents and settings\...). this causes problems while building. to avoid this issue, change to a directory without spaces (i.e. c:\ ) before doing the following steps. you can use the "cd" command to do so. # get the source hg clone http://hg.mozilla.org/comm-central/ cd comm-central python client.py checkout # setup a basic .mozconfig file echo 'ac_add_options --enable-application=calendar' > .mozconfig # let's build sunbird... echo 'mk_add_options moz_objdir=@topsrcdir@/objdir-sb-release' >> .mozconfig # ...in this...
... objdir-sb-release/dist/calendar.app/contents/macos/). building sunbird and lightning if you've set up you build environment as above, then all you need to do is: echo 'ac_add_options --enable-calendar' >> .mozconfig or just add the ac_add_options --enable-calendar line to your .mozconfig with your favourite editor. then just re-run the "make -f client.mk" command above (you can do the addition before running make for the first time). this will build the lightning extension into src/../objdir-sb/mozilla/dist/xpi-stage/. see this section for information on how to easily integrate lightning into a nightly version of thunderbird. how to build again later in your comm-central directory, run these commands: # get the latest source python client.py checkout then just re-run the "make -f client.mk"...
Simple Thunderbird build
onger has any effect. if it is in your `mozconfig` file, you should go ahead and remove it when building thunderbird 74 or later, since support for it will eventually be removed completely. add the following line to your mozconfig file: ac_add_options --enable-calendar to add that line you can do this in the source/ directory: echo 'ac_add_options --enable-calendar' >> mozconfig building before you start, make sure that the version you checked out is not busted. for hg tip, you should see green bs on https://treeherder.mozilla.org/#/jobs?repo=comm-central to start the build, cd into the source directory, and run: ./mach build mach is our command-line tool to streamline common developer tasks. see the mach article for more. building can take a significant amount of time, depending o...
...tual error is. check if your mozilla/ is a symlink. a symlink there is not supported. check for @topsrcdir@ or relative paths in your mozconfig. those have caused several problems historically and tend to be poorly tested when the build system changes. if on windows you get link errors like "lnk1102: out of memory" or "lnk1318: unexpected pdb error; ok (0)", try deleting the largest .pdb files before rushing out the door to buy more ram. clobbering (see below) will also remove those files. try with a clean obj-dir. you can clean out previous build artefacts using ./mach clobber references general build documentation comm-central using the mozilla symbol server ...
ESLint
onfiguration files have been added to the code base so that javascript can be analyzed automatically. this automatic linting can happen either while coding, in a code editor, or when using the command line. it also runs on treeherder for every check-in. running eslint eslint comprises of a set of rules that are used to analyse the code for correctness and style consistency. meeting these rules before review will help reduce the amount of review time, and the revisions necessary to have a review granted. setting up eslint ./mach eslint --setup running eslint eslint can be run via: ./mach lint -l eslint you can limit running it to a specific directory with: ./mach lint -l eslint browser/components or work directory changes: ./mach lint -l eslint -w or outgoing commits only: ./mach li...
...hanges: ./mach lint -l eslint -w or outgoing commits only: ./mach lint -l eslint -o see ./mach eslint --help for more options when running eslint. vcs hooks hooks are available for mercurial & git, see using a vcs hook for more details. editor integration it is highly recommended that you integrate eslint into your editor. this lets you see errors in real time, and can help you fix issues before you compile or run tests, reducing the time to develop patches. see the eslint user guide for which plugins to install in your editor. prior to firefox 55 the location for the eslint binary used to be tools/lint/eslint/node_modules/.bin, since bug 1305023, node_modules is now located in the top-level directory, and should need no special set-up. understanding rules and errors not all files ...
Gecko Logging
ng level is enabled. if (moz_log_test(slogger, loglevel::warning)) { int elapsed = time::nowms() - start; if (elapsed > 1000) { moz_log(slogger, loglevel::warning, ("loop took %dms!", elapsed)); } } if (i != 10) { moz_log(slogger, loglevel::error, ("i should be 10!")); } } enabling logging the log level for a module is controlled by setting an environment variable before launching the application. it can also be adjusted by setting prefs. by default all logging output is disabled. set moz_log="example_logger:3" in the windows command prompt (cmd.exe), don't use quotes: set moz_log=example_logger:3 if you want this on geckoview example, use the following adb command to launch process: adb shell am start -n org.mozilla.geckoview_example/.geckoviewactivity ...
...ple/.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 synchronously, this is useful to check behavior in real time or get logs immediately before crash. raw print exactly what has been specified in the format string, without the process/thread/timestamp, etc. prefix. timestamp insert timestamp at start of each log line. rotate:n this limits the produced log files' size. only most recent n megabytes of log data is saved. we rotate four log files with .0, .1, .2, .3 extensions. note: this option disable...
Obsolete Build Caveats and Tips
on in the ui thunderbird windows search integration text services framework support there are two ways to obtain it: download the windows vista sdk from the microsoft download center. you may choose not to install the sample code and documentation to save space and download time. if you are using windows xp, you must have windows xp service pack 2 and .net framework 2.0 installed before installing the vista sdk. use visual studio 2008 professional. gecko 1.9.2 through 11: if you would like to use this sdk, add ac_add_options --with-windows-version=600 to your .mozconfig. windows server 2003 r2 platform sdk obsolete since gecko 12.0 (firefox 12.0 / thunderbird 12.0 / seamonkey 2.9)this feature is obsolete. although it may still work in some browsers, its use is discou...
...); this will build something roughly the same as the shipped version of firefox corresponding to the code you have. you only need to follow the steps below if you want to customize the build (e.g., to create a debug build or a release build with debug symbols), you want to build something other than firefox, or you want to build pre-gecko 5.0 source. if you are building mozilla source code from before firefox 5, then you must first select the mozilla application that you want to build (see below), and you will probably also need to set at least some of the other basic configuration options (such as whether to build a debug build or not) to get the type of build that you need. if you are building from an older project branch that still uses cvs, you will need to set moz_co_project to the app...
Embedding Tips
ing, stopping a load and going back and forward in the history. how do i block a load? implement the nsiwebprogresslistener interface and register it with the appropriate web browser object via the nsiwebbrowser::addwebbrowserlistener() method. use the callbacks for after-the-fact cancellation. alternatively, implement a nsiuricontentlistener as described below. how do i watch/intercept a load before it happens? implement the nsiuricontentlistener interface, and register it with the appropriate web browser object via the nsiwebbrowser::parenturicontentlistener attribute. watch for changes in nsiuricontentlistener::onstarturiopen(). you can abort the uri load at this point if you don't want it to proceed. if necessary you may also implement the nsiuricontentlistener::ispreferred(), returning...
...r more information. for example, if you wanted to check the server response headers, you might check onstatechange for state_start | state_is_request flags, and from the nsirequest argument qi fornsihttpchanne and call methods on that to determine response codes and other information from the server. it is left as an exercise to make this sample synchronous, i.e. wait for persistence to complete before returning. hint, add a native message processing loop after the call to saveuri that terminates when onstatechange indicates persistence has finished.. how do i print a page? query the web browser object for nsiwebbrowserprint. call the nsiwebbrowserprint::print() method supplying a print settings object (e.g. that returned from nsiwebbrowserprint::getglobalprintsettings) that you wish to print...
Geckoview-Junit Tests
y a host (typically linux) using mozdevice (adb). in automation, tests normally run in an android emulator. running tests locally if desired, connect an android device to your computer, or start an emulator, and make sure your device is visible to adb: $ adb devices list of devices attached emulator-5554 device if no device is found, 'mach geckoview-junit' will offer to start an emulator. before running tests, install the androidtest apk on your device; otherwise, 'mach geckoview-junit' will offer to install it. mozilla-central$ mach install --app org.mozilla.geckoview.test to run all tests: mozilla-central$ mach geckoview-junit to run just one class of tests: mozilla-central$ mach geckoview-junit <class> please note that unlike robocop tests, <class> needs to be specified using ...
...st be listed on its own line. for example: <class1>#<test1> <class2> <class3>#<test2> <class3>#<test3> to run the tests specified in the file: mozilla-central$ mach geckoview-junit --test-filters-file <path-to-filter-file> disabling one failing test there is no manifest listing the geckoview junit tests. to disable a single test, edit the source code and insert junit's @ignore annotation before the existing @test annotation. for example: import org.junit.ignore ... @runwith(testrunner.class) public class testsomethings { @ignore @test public void testsomething() { ... tests can also be conditionally skipped using junit's assume or assumethat methods. for example: import org.junit.assume.assumethat ... @test fun contentcrashignored() { // cannot test x86 debug b...
HTTP Cache
he entry remains empty (a.k.a. "new"). the writer stored all necessary meta data in the cache entry and called metadataready on it: other consumers now get the entry and may examine and potentially modify the meta data and read the data (if any) of the cache entry. when the writer has data (i.e. the response payload) to write to the cache entry, it must open the output stream on it before it calls metadataready. when the writer still keeps the cache entry and has open and keeps open the output stream on it, other consumers may open input streams on the entry. the data will be available as the writer writes data to the cache entry's output stream immediately, even before the output stream is closed. this is called concurrent read/write. concurrent read and write important...
...e) the writer (in this order) opens the output stream on the cache entry and calls setvalid to unblock other pending openers. concurrent read/write is engaged. lifetime of an existing entry that doesn't pass server revalidation such a cache entry is first examined in the nsicacheentryopencallback.oncacheentrycheck callback, where the consumer finds out it must be revalidated with the server before use. the consumer then indicates the cache entry needs to be revalidated by returning entry_needs_revalidation from oncacheentrycheck. this consumer, from the point of view the cache, takes a role of the writer. other parallel consumers, if any, are blocked until the writer calls setvalid on the cache entry. the consumer is then responsible to validate the partial content cache entry with the...
How to get a stacktrace with WinDbg
nd open windbg from the start menu. (start->all programs->debugging tools for windows->windbg) next, open the "file" menu and choose "open executable...". in the file chooser window that appears, open the firefox.exe executable in your firefox program folder (c:\program files\mozilla firefox). you should now see a "command" text window with debug output at the top and an input box at the bottom. before debugging can start, several commands must be entered into the one-line input box at the bottom of the command window. tip: all commands must be entered exactly as written, one line at a time, into the bottom of the command box. copying and pasting each line is the easiest method to avoid mistakes some commands start with a period (.) or a pipe character (|), which is required. (the keystro...
...d record a log of loaded modules. you will also want to open a log file to save data you collect. to do this, enter these four commands, pressing enter after each one. .logopen /t c:\temp\firefox-debug.log .childdbg 1 .tlist sxn gp lm if you see firefox.exe listed in the output from .tlist more than once, then you are already running the application and need to close the running instance first before you start debugging, otherwise you won't get useful results. now run firefox by opening the debug menu and clicking go. while firefox is running, you will not be able to type any commands into the debugger. after it starts, try to reproduce the crash or hanging issue that you are seeing. if firefox fails to start, and you see lines of text followed by a command prompt in the debugger, a "breakp...
How to implement a custom autocomplete search component
const ci = components.interfaces; const cu = components.utils; cu.import('resource://gre/modules/xpcomutils.jsm'); const class_id = components.id('x753d830-ba1e-11e0-962b-0800200c9a66'); // ← change this const class_name = "basic autocomplete"; const contract_id = '@mozilla.org/autocomplete/search;1?name=basic-autocomplete'; /** * @constructor * * @implements {nsiautocompleteresult}...
... const ci = components.interfaces; const class_id = components.id("6224daa1-71x2-4d1a-ad90-01ca1c08e323"); // ← change this const class_name = "simple autocomplete"; const contract_id = "@mozilla.org/autocomplete/search;1?name=simple-autocomplete"; // implements nsiautocompleteresult function simpleautocompleteresult(searchstring, searchresult, defaultin...
How to Report a Hung Firefox
the crash report link for a hang, obtained by following the steps below. submit a crash report for a hung firefox the easiest way to help the firefox stability team to debug these kinds of hangs is to make the hung firefox crash a...
... the crash report link for a hang, obtained by following the steps below. ...
IPDL Best Practices
lifetime management ensure ipdl deletes your protocol all protocols must be deleted. period. are you sending the __delete__ message to trigger protocol deletion? this one is easy to miss, as the corresponding recv__delete__ function has a stub implementation automatically generated in the base class. simply calling delete on a pointer to an actor is not enough. ...
... is that you absolutely, certainly, positively call send__delete__ in all possible circumstances or your protocol can and will leak. calling ipdl functions willy-nilly let's say you have an object that implements an ipdl interface, but it also outlives it (case in point: reference-counted). is there any chance that an ipdl function could be called after the protocol itself has been destroyed, or before it has been created? don't let it happen - that is a guaranteed crash right there. use a flag and the generated actordestroy function to control when ipdl functions can be called; see phttpchannelparent/child for an example. when to run code here's a rundown on appropriate places to run certain kinds of code: manager::allocpprotocol - allocation manager::recvpprotocolconstructor - initiali...
DownloadSummary
ise addview(object aview); promise removeview(object aview); properties attribute type description allhavestopped read only boolean indicates whether all the downloads are currently stopped. progresstotalbytes read only number indicates the total number of bytes to be transferred before completing all the downloads that are currently in progress. for downloads that do not have a known final size, the number of bytes currently transferred is reported as part of this property. this is zero if no downloads are currently in progress. progresscurrentbytes read only number number of bytes currently transferred as part of all...
... progresscurrentbytes read only number number of bytes currently transferred as part of all the downloads that are currently in progress. this is zero if no downloads are currently in progress. methods bindtolist() this method may be called once to bind this object to a downloadlist. views on the summarized data can be registered before this object is bound to an actual list. this allows the summary to be used without requiring the initialization of the downloadlist first. note: this method is already called internally by the downloads.getsummary() function. promise bindtolist( downloadlist alist ); parameters alist underlying downloadlist whose contents should be summarized. promise resolves to undefined w...
Following the Android Toasts Tutorial from a JNI Perspective
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. for example, navigating away from an email before you send it triggers a "draft saved" toast to let you know that you can continue editing later. toasts automatically disappear after a timeout. toasts do not have to be created with jni; they are exposed by the nativewindow feature on firefox for android, see toast documentation. java code let's start with the following java code, which invokes a toast and says "hello, firefox!". context cont...
... we see that the signature in dot notation is android.content.context. so this will be written as landroid/content/context;. for convenience, let's make an object called sig and populate it with our types. let sig = { context: 'landroid/content/context;', charsequence; 'ljava/lang/charsequence;', int: 'i', toast: 'landroid/widget/toast;', void: 'v', }; get java environment before we go on to declare the other important features, we need to load our environment variable. we want to wrap this in a try-catch statement so if any errors occur we make sure to unload the classes and the java environment, this is good for performance. this is the template that will follow our object of signatures: var my_jenv = null; try { my_jenv = jni.getforthread(); // do the jni wo...
Promise
y in the pending state, and provides references to the resolving functions that can be used to change its state. new promise(executor); parameters executor this function is invoked immediately with the resolving functions as its two arguments: executor(resolve, reject); the constructor will not return until the executor has completed. the resolving functions can be used at any time, before or after the executor has completed, to control the final state of the promise. if the executor throws an exception, its value will be passed to the reject resolving function. resolving functions resolve() fulfills the associated promise with the specified value, or propagates the state of an existing promise. if the associated promise has already been resolved, either to a value, a rejecti...
...nction. resolving functions resolve() fulfills the associated promise with the specified value, or propagates the state of an existing promise. if the associated promise has already been resolved, either to a value, a rejection, or another promise, this method does nothing. note: calling this method with a pending promise as the avalue argument, and then calling it again with another value before the promise is fulfilled 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 p...
PromiseWorker.jsm
ost(afunctionname, aargs, aclosure, atransferlist); parameters afunctionname the name of the function to be called as it appears in the worker file. aargs an array of arguments to pass to the function named afunctionname in the worker file. if the worker function does not have any arguments and the empty array should be passed here. if any of the arguments is a promise, it is resolved before posting the message. if any of the arguments needs to be transferred instead of copied, this may be specified by making the argument an instance of basepromiseworker.meta or by using the atransferlist argument. by convention, the last argument may be an object options with some of the following fields: outexecutionduration {number|null} a parameter to be filled with the duration of the o...
...of basepromiseworker.meta or by using the atransferlist argument. by convention, the last argument may be an object options with some of the following fields: outexecutionduration {number|null} a parameter to be filled with the duration of the off main thread execution for this call. aclosure optional an object holding strong references to value that should not be garbage-collected before the reply has been received. atransferlist optional an optional array of transferable objects to transfer ownership of. if the ownership of an object is transferred, it becomes unusable (neutered) in the context it was sent from, and it becomes available only to the worker it was sent to. only messageport and arraybuffer objects can be transferred. to learn more on how to achieve this see the ...
Using JavaScript code modules
nto the importing scope. for example: components.utils.import("resource://app/my_module.jsm"); alert(foo()); // displays "foo" alert(bar.size + 3); // displays "6" alert(dummy); // displays "dummy is not defined" because 'dummy' was not exported from the module note: when you're testing changes to a code module, be sure to change the application's build id (e.g., the version) before your next test run; otherwise, you may find yourself running the previous version of your module's code. the url for a code module as you can see from the example above, you need a url to import a code module. (the url in the example is "resource://app/my_module.jsm".) code modules can only be loaded using a chrome: (), resource:, or file: url. if you're writing an extension for firefox 4 a...
...this means you can't use components.utils.import() with your own resource url at the top level in a component source. a possible solution is moving the call to components.utils.import() into the xpcom component constructor (discussion). packaging notes it's important to note that you should not typically put your javascript code modules in a jar file in your add-on. firefox...
source-editor.jsm
fired when the editor loses focus. sourceeditor.events.breakpoint_change "breakpointchange" fired when a new breakpoint is added, or when an existing breakpoint is removed. this happens both when the api is used to make the change or when the ui is used to do it. sourceeditor.events.context_menu "contextmenu" fired when the editor's context menu is invoked, but before it's opened. sourceeditor.events.dirty_changed "dirtychanged" fired when the dirty state of the editor is changed. the dirty state indicates whether or not there are unsaved changes to the text. sourceeditor.events.focus "focus" fired when the editor gains focus. sourceeditor.events.mouse_move "mousemove" fired when the user moves the mouse over a li...
... returns the line number of the first line currently visible in the editor, based on the current scroll position of the editor. number gettopindex(); parameters none. return value the line number of the first visible line; this is a 0-based value, so the first line of the document is line number 0. init() initializes the editor. you must call this, and wait until your callback is called, before calling any other source editor methods. void init( element aelement, object aconfig function acallback ); parameters aelement the dom element in which to place the editor. aconfig an object containing a set of properties used to configure the editor. see the editor configuration object for details. acallback a function that will be called when the editor has been fully loaded an...
Localization content best practices
ish/gaelic the correct order is be [username] at saying:. if a placeholder is present, this can be correctly localized as tá %s ag rádh: but not without. similarly, if the ui string is flash version, do not simply present the translator with version for translation. present the whole string or, if there is a significant need for a placeholder, use a placeholder. the word version may have to go before or after flash and one or both may need to be inflected. idiom idiom, in a loose sense, also has an impact on localization if it leads to strings being prepared in a way that renders them unlocalizable. for example, in english all the following begin with the same clause: the url of this feed is invalid; the url of this feed cannot be reached; the url of this feed cannot be parsed. it might be ...
...ter not available in the original string, given entities "usebookmark.label" and "usebookmark.accesskey", if you change to "choosebookmark.label" due to a string change, change the access key entity to "choosebookmark.accesskey" to match it. string freeze some repositories are considered to be string-frozen. this means that string changes are not allowed to land, and each case must be evaluated before landing. as a general rule, it's recommended to fix strings on the trunk/master repository, and create ad-hoc patches for string frozen repositories that don't involve string changes. note that even removing strings is considered a breakage. in the case of firefox and thunderbird, string frozen repositories are: mozilla-aurora, mozilla-beta, mozilla-release. bugzilla and l10n do i need l10n fe...
Localizing with Mercurial
work? open a terminal window and type hg --version. if you see a message about the version of mercurial (e.g. mercurial distributed scm (version 1.3.1)), you have installed mercurial successfully! more details for more details on installing hg on mac osx, refer to the instructions on mercurial's download page. configuring mercurial once you've installed mercurial, you'll need to configure it before you can use it successfully. your mercurial configuration is contained within a config file which you must create yourself. your config file is called either ~/.hgrc (unix systems) or mercurial.ini (windows), depending on your operating system. your config file should have the following settings: [ui] username = your real name <user@example.com> merge = internal:merge [defaults] commit = -v ...
...or peers of a localization, the owner can vouch (once she or he is registered). sending changes to mozilla now that you have hg account privileges, you can send your work to mozilla all by yourself. here are the steps to send your l10n work using mercurial: since your l10n work takes place in your own local repository, you should ensure that there are no changes made to the remote repository before committing your work. to do this, update your locale, as per the section above. after finishing a change or set of changes and checking you have updated to the latest, you should commit by entering this command: hg commit -m "your message identifying the change (bug 555)" committing won’t send your changes to mozilla’s repository, but prepares them for it. the next step will send your cha...
Mozilla Quirks Mode Behavior
g 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). support <pre wrap>, <pre cols>, <pre width>. orphaned dd has generated content :before instead of margin (bug 5119). indent nested dl elements (bug 8749). map acts like an inline, not a block. give floated img a 3px margin (bug 58899). residual style tags' size info does not take precedence over heading tags' size (bug 77352). use box-sizing:border-box for most input types and textarea. give form a margin-bottom:1em (bug 41806). in quirks mode css class and...
... in quirks mode, text-decoration is propagated into floating and absolutely positioned elements. (firefox 4 / thunderbird 3.3 / seamonkey 2.1) in quirks mode, text-decoration is not propagated into tables (bug 572713). maybe (firefox 3) when computing the minimum intrinsic width of an inline flow directly in a table cell (no blocks in between), it is assumed that it is not possible to break before and after an image (when otherwise it would be). obsolete since gecko 8.0 prior to gecko 8.0 (firefox 8.0 / thunderbird 8.0 / seamonkey 2.5) text-decoration in quirks mode had line thickness and position adjusted on descendant text to match the descendant. tables td, th, tr, thead, tbody, and tfoot elements have the document background (and color?) applied to them (when the document backgro...
Profiling with Xperf
o a registry tweak and then restart to enable stack walking: reg add "hklm\system\currentcontrolset\control\session manager\memory management" -v disablepagingexecutive -d 0x1 -t reg_dword -f symbol server setup with the latest versions of the windows performance toolkit, you can modify the symbol path directly from within the program via the trace menu. just make sure you set the symbol paths before enabling "load symbols" and before opening a summary view. you can also modify the _nt_symbol_path and _nt_symcache_path environment variables to make these changes permanent. the standard symbol path that includes both mozilla's and microsoft's symbol server configuration is as follows: _nt_symcache_path: c:\symbols _nt_symbol_path: srv*c:\symbols*http://msdl.microsoft.com/download/symbols;srv...
...events (heap allocations outstanding, etc. all lead to the same summary graphs), 3 types of allocations are listed -- aifi, aifo, aofi. this is shorthand for "allocated inside, freed inside", "allocated inside, freed outside", "allocated outside, freed inside". these refer to the time range that was selected for the summary graph; for example, something that's in the aofi category was allocated before the start of the selected time range, but the free event happened inside. tips in the summary views, the yellow bar can be dragged left and right to change the grouping -- for example, drag it to the left of the module column to have grouping happen only by process (stuff that's to the left), so that you get symbols in order of weight, regardless of what module they're in. dragging the columns...
Reporting a Performance Problem
self for 5-10 seconds. press ctrl+shift+2 or click on the profiler toolbar icon in the top right and select 'capture'. try to do this within a few seconds from reproducing the performance problem as only the last few seconds are recorded. if the timeline has a large red block it's a good sign. the data will open in a new tab. wait until the "symbolicating call stacks" notification disappears before sharing the profile. there will be a button in the top right labeled 'publish' which will allow you to upload this profile and once completed will write out a link. before uploading, the publish button asks you what data you'd like to publish to our servers. note that while it's possible to strip profiles of potentially privacy sensitive information, the less information a profile contains, the...
...wn. you might have a content process using up the cpu and not the main one. make sure you are doing whatever it is that slows down firefox while recording the profile. for example you might have one addon that slows down page load and another one that slows down tab switch. your first reflex once you find what addon is slowing down the profile might be to disable it and search for alternatives. before you do this, please share the performance profile with the addon authors through a bug report. gecko profiler allows you to share a link with the profile. ...
TimerFirings logging
he code uses dladdr to get the name immediately, and the output will look like the following. 2082435840[100445640]: [81190] fn timer (one_shot 8000 ms): [from dladdr] gfxfontinfoloader::delayedstartcallback(nsitimer*, void*) second, on linux the code uses dladdr to get the symbol library and address, which can be post-processed by tools/rb/fix_stacks.py. the following two lines show the output before and after being post-processed by that script. 2088737280[7f606bf68140]: [30710] fn timer (one_shot 16 ms): [from dladdr] #0: ???[/home/njn/moz/mi1/o64/dist/bin/libxul.so +0x2144f94] 2088737280[7f606bf68140]: [30710] fn timer (one_shot 16 ms): [from dladdr] #0: mozilla::refreshdrivertimer::timertick(nsitimer*, void*) (/home/njn/moz/mi1/o64/layout/b third, on other platforms dladd...
...1193354?:83:0 94 801266240[7f7c1f248000]: [7163] fn timer (one_shot 160 ms): nsbrowserstatusfilter::timeouthandler 92 -495057024[7f74e105ba00]: [7108] fn timer (one_shot 160 ms): nsbrowserstatusfilter::timeouthandler the first column shows how many times the particular line appeared. it is sometimes useful to pre-process the output by stripping out certain parts of each line before doing this aggregation step, for example, by inserting one or more of the following commands into the command pipeline. sed 's/^[^:]\+: //' # strip thread ids sed 's/\[[0-9]\+\] //' # strip process ids sed 's/ \+[0-9]\+ ms//' # strip timer periods the following is the previous sample output with all three of these commands added into the pipeline. 204 fn timer (o...
about:memory
k "measure..." repeatedly, because that will cause the memory usage of about:memory itself to rise, due to it discarding and regenerating large numbers of dom nodes. note that in both cases the generated data contains privacy-sensitive details such as the full list of the web pages you have open in other tabs. if you do not wish to share this information, you can select the "anonymize" checkbox before clicking on "measure and save..." or "measure...". this will cause the privacy-sensitive data to be stripped out, but it may also make it harder for others to investigate the memory usage. loading memory reports from file the easiest way to load memory reports from file is to use the "load..." button. you can also use the "load and diff..." button to get the difference between two memory report...
...ascript ("js-compartment(...)" and "js-zone(...)"), layout, style-sheets, the dom, and other things. it's clear that the cnn.com tab is using more memory than the techcrunch.com tab, which is using more than the arstechnica.com tab. sub-trees with names like "(2 tiny)" are artificial nodes inserted to allow insignificant sub-trees to be collapsed by default. if you select the "verbose" checkbox before measuring, all trees will be shown fully expanded and no artificial nodes will be inserted. the "js-non-window" sub-tree represents javascript memory usage that doesn't come from windows, but from the browser core. the "heap-unclassified" value represents heap-allocated memory that is not measured by any memory reporter. this is typically 10--20% of "explicit". if it gets higher, it indicates t...
Optimizing Applications For NSPR
gives control to windows. windows 3.1 applications always run on a stack provided by windows. this means that nspr threads use a shadow stack to preserve context across a thread switch. at thread switch time, the stack of the current running thread is copied to other storage associated with that thread and the about-to-be-dispatched thread's stack data is copied back onto the windows stack just before the thread is given control. this has disastrous implications on the generally accepted programming practice of taking the address of a stack variable and giving that address to another thread. consider that the windows stack is swapped in and out with each thread switch. the thread that created a stack variable sees his own stack variables correctly across thread switches. however, another thre...
..._error</tt>. the only thing you can do is to close the file descriptor. see the faq article for more info. there is no current workaround. you must write your program with this restriction in mind. pr_interrupt is implemented except for <tt>pr_connect()</tt>. irix the irix (classic) implementation has a known race condition in creating new threads. if the spawned thread establishes and exits before the parent thread is resumed, the parent will be left with an invalid pointer to the child. the problem has a solution that will be available soon. digital unix digital unix (aka, osf1) requires the latest patches for the pthreads library. the changes are not evident until one tries to do thread suspension (<tt>pr_suspendall()</tt>) which is in preparation for garbage collection. digital uni...
Monitors
in addition to the mutex type prlock, nspr provides a special type, prmonitor, for use in java programming. this chapter describes the nspr api for creation and manipulation of a mutex of type prmonitor. monitor type monitor functions with a mutex of type prlock, a single thread may enter the monitor only once before it exits, and the mutex can have multiple associated condition variables. with a mutex of type prmonitor, a single thread may re-enter a monitor as many times as it sees fit. the first time the thread enters a monitor, it acquires the monitor's lock and the thread's entry count is incremented to 1. each subsequent time the thread successfully enters the same monitor, the thread's entry count is incremented again, and each time the thread exits the monitor, the thread's entry...
...in, and each time the thread exits the monitor, the thread's entry count is decremented. when the entry count for a thread reaches zero, the thread releases the monitor's lock, and other threads that were blocked while trying to enter the monitor will be rescheduled. a call to pr_wait temporarily returns the entry count to zero. when the calling thread resumes, it has the same entry count it had before the wait operation. unlike a mutex of type prlock, a mutex of type prmonitor has a single, implicitly associated condition variable that may be used to facilitate synchronization of threads with the change in state of monitored data. for an introduction to nspr thread synchronization, including locks and condition variables, see introduction to nspr. monitor type with the exception of pr_newm...
PR_CWait
or's state has changed. syntax #include <prcmon.h> prstatus pr_cwait( void *address, printervaltime timeout); parameters the function has the following parameters: address the address of the protected object--the same address previously passed to pr_centermonitor. timeout the amount of time (in printervaltime units) that the thread is willing to wait for an explicit notification before being rescheduled. if you specify pr_interval_no_timeout, the function returns if and only if the object is notified. returns the function returns one of the following values: pr_success indicates either that the monitored object has been notified or that the interval specified in the timeout parameter has been exceeded. pr_failure indicates either that the monitor could not be located in ...
...alue specified in the address parameter to find a monitor in the monitor cache, pr_cwait waits for a notification that the monitor's state has changed. while the thread is waiting, it exits the monitor (just as if it had called pr_cexitmonitor as many times as it had called pr_centermonitor). when the wait has finished, the thread regains control of the monitor's lock with the same entry count as before the wait began. the thread waiting on the monitor resumes execution when the monitor is notified (assuming the thread is the next in line to receive the notify) or when the interval specified in the timeout parameter has been exceeded. when the thread resumes execution, it is the caller's responsibility to test the state of the monitored data to determine the appropriate action. ...
PR_TransmitFile
, const void *headers, print32 hlen, prtransmitfileflags flags, printervaltime timeout); parameters the function has the following parameters: networksocket a pointer to a prfiledesc object representing the connected socket to send data over. sourcefile a pointer to a prfiledesc object representing the file to send. headers a pointer to the buffer holding the headers to be sent before sending data. hlen length of the headers buffer in bytes. flags one of the following flags: pr_transmitfile_keep_open indicates that the socket will be kept open after the data is sent. pr_transmitfile_close_socket indicates that the connection should be closed immediately after successful transfer of the file. timeout time limit for completion of the transmit operation. returns ...
... file. the value -1 indicates a failure. if an error occurs while sending the file, the pr_transmitfile_close_socket flag is ignored. the reason for the failure can be obtained by calling pr_geterror. description the pr_transmitfile function sends a complete file (sourcefile) across a connected socket (networksocket). if headers is non-null, pr_transmitfile sends the headers across the socket before sending the file. the enumeration prtransmitfileflags, used in the flags parameter, is defined as follows: typedef enum prtransmitfileflags { pr_transmitfile_keep_open = 0, pr_transmitfile_close_socket = 1 } prtransmitfileflags; ...
PR_Wait
.h> prstatus pr_wait( prmonitor *mon, printervaltime ticks); parameters the function has the following parameter: mon a reference to an existing structure of type prmonitor. the monitor object referenced must be one for which the calling thread currently holds the lock. ticks the amount of time (in printervaltime units) that the thread is willing to wait for an explicit notification before being rescheduled. returns the function returns one of the following values: pr_success means the thread is being resumed from the pr_wait call either because it was explicitly notified or because the time specified by the parameter ticks has expired. pr_failure means pr_wait encountered a system error (such as an invalid monitor reference) or the thread was interrupted by another thread. ...
...ence) or the thread was interrupted by another thread. description a call to pr_wait causes the thread to release the monitor's lock, just as if it had called pr_exitmonitor as many times as it had called pr_entermonitor. this has the effect of making the monitor available to other threads. when the wait is over, the thread regains control of the monitor's lock with the same entry count it had before the wait began. a thread waiting on the monitor resumes when the monitor is notified or when the timeout specified by the ticks parameter elapses. the resumption from the wait is merely a hint that a change of state has occurred. it is the responsibility of the programmer to evaluate the data and act accordingly. this is usually done by evaluating a boolean expression involving the monitored dat...
Introduction to Network Security Services
ed libraries (such as libnss3.so) are installed. both shared libs should always be installed whether the target system has a 32-bit cpu or a 64-bit cpu. nss will pick the right one for the local system at run time. note that nss 3.x is also available in the lp64 model for these platforms, but the lp64 model of nss 3.x does not have these two extra shared libraries. ...
... as mentioned above, nss is built on top of nspr. ...
JSS FAQ
Mozilla › Projects › NSS › JSS › JSS FAQ
turn the local certificate for ssl client auth. jss's two callbacks are: sslcertificateapprovalcallback is a combination of ssl_authcertificatehook and ssl_badcerthook. it runs nss's cert authentication check, then calls the callback regardless of whether the cert passed or failed. the callback is told whether the cert passed, and then can do anything extra that it wants to do before making a final decision. sslclientcertificateselectioncallback is analogous to ssl_getclientauthdatahook. can i have multiple jss instances reading separate db's? no, you can only have one initialized instance of jss for each database. once jss initialized, i can't get anymore instances with certificatefactory.getinstance("x.509")? in version previous to jss 3.1...
....certificate? import java.io.bytearrayinputstream; [...] certificate cert = (certificate) asn1util.decode( certificate.gettemplate(),x509cert.getencoded() ); how do i convert org.mozilla.jss.pkix.cert to org.mozilla.jss.crypto.x509certificate? cryptomanager.importcertpackage() is it possible to use jss to acces cipher functionality from pkcs11 modules? yes. before jss 3.2 you would use cryptomanager to obtain the cryptotoken you want to use, then call cryptotoken.getciphercontext() to get an encryption engine. but as of jss 3.2 you would use the jss jca provider. can you explain token names and keys with regards to jss? the token name is different depending on which application you are running. in jss, the token is called "internal key storage tok...
Using JSS
Mozilla › Projects › NSS › JSS › Using JSS
t this directory in your classpath to run applications locally; or, you can package the class files into a jar file for easier distribution: cd mozilla/dist/classes[_dbg] zip -r ../jss42.jar . if you are downloading binaries, get jss42.jar from http://ftp.mozilla.org/pub/mozilla.org/security/jss/releases/. setup your runtime environment you need to set some environment variables before building and running java applications with jss. classpath include the path containing the jss classes you built, or the path to jss42.jar. (the path to jss34.jar ends with the string "/jss42.jar". it is not just the directory that contains jss42.jar.) ld_library_path (unix) / path (windows) include the path to the nspr, nss, and jss shared libraries. initial...
...plications with jss. classpath include the path containing the jss classes you built, or the path to jss42.jar. (the path to jss34.jar ends with the string "/jss42.jar". it is not just the directory that contains jss42.jar.) ld_library_path (unix) / path (windows) include the path to the nspr, nss, and jss shared libraries. initialize jss in your application before calling any jss methods, you must initialize jss by calling one of the cryptomanager.initialize methods. see the javadoc for more details. ...
NSS_3.12_release_notes.html
ences in pk11obj.c bug 353780: klocwork null ptr dereferences in pkcs11.c bug 353865: klocwork null ptr deref in softoken/pk11db.c bug 353888: klockwork ids for ssl3con.c bug 353895: klocwork null ptr derefs in pki/pkibase.c bug 353902: klocwork bugs in stanpcertdb.c bug 353903: klocwork oom crash in softoken/keydb.c bug 353908: klocwork oom crash in tdcache.c bug 353909: klocwork ptr dereference before null check in devutil.c bug 353912: misc klocwork bugs in lib/ckfw bug 354008: klocwork bugs in freebl bug 359331: modutil -changepw strict shutdown failure bug 373367: verify ocsp response signature in libpkix without decoding and reencoding bug 390542: libpkix fails to validate a chain that consists only of one self issued, trusted cert bug 390728: pkix_pl_ocsprequest_create throws an error if ...
...es -b time option when -p option is present bug 403563: implement the tls session ticket extension (ste) bug 400917: want exported function that outputs all host names for dns name matching bug 315643: test_buildchain_resourcelimits won't build bug 353745: klocwork null ptr dereference in pkcs12 decoder bug 338367: the gf2m_populate and gfp_populate should check the eccurve_map array index bounds before use bug 201139: ssltap should display plain text for null cipher suites bug 233806: support nist crl policy bug 279085: nss tools display public exponent as negative number bug 363480: ocspclnt needs option to take cert from specified file bug 265715: remove unused hsearch.c dbm code bug 337361: leaks in jar_parse_any (security/nss/lib/jar/jarver.c) bug 338453: leaks in security/nss/lib/jar/jarfi...
NSS 3.48 release notes
bug 1590001 - prevent negotiation of versions lower than 1.3 after helloretryrequest bug 1596450 - added a simplified and unified mac implementation for hmac and cmac behind pkcs#11 bug 1522203 - remove an old pentium pro performance workaround bug 1592557 - fix prng known-answer-test scripts bug 1586176 - encryptupdate should use maxout not block size (cve-2019-11745) bug 1593141 - add `notbefore` or similar "beginning-of-validity-period" parameter to mozilla::pkix::trustdomain::checkrevocation bug 1591363 - fix a pbkdf2 memory leak in nsc_generatekey if key length > max_key_len (256) bug 1592869 - use arm neon for ctr_xor bug 1566131 - ensure sha-1 fallback disabled in tls 1.2 bug 1577803 - mark pkcs#11 token as friendly if it implements ckp_public_certificates_token bug 1566126 - p...
...y_len (256) bug 1592869 - use arm neon for ctr_xor bug 1566131 - ensure sha-1 fallback disabled in tls 1.2 bug 1577803 - mark pkcs#11 token as friendly if it implements ckp_public_certificates_token bug 1566126 - power ghash vector acceleration bug 1589073 - use of new pr_assert_arg in certdb.c bug 1590495 - fix a crash in pk11_makecertfromhandle bug 1591742 - ensure des iv length is valid before usage from pkcs#11 bug 1588567 - enable mozilla::pkix gtests in nss ci bug 1591315 - update nsc_decrypt length in constant time bug 1562671 - increase nss mp kdf default iteration count, by default for modern key4 storage, optionally for legacy key3.db storage bug 1590972 - use -std=c99 rather than -std=gnu99 bug 1590676 - fix build if arm doesn't support neon bug 1575411 - enable tls exten...
NSS API Guidelines
and entire books about how to safely access data on lists. some simple strategies and their issues: use hash tables: hash table lookups are usually quite fast, limiting the contention on the lock. this is best for large lists of objects. be sure to calculate the hash value first, then only lock over the hash table value itself. be sure to increment the reference count, on the returned object, before unlocking. examples of hash tables can be found in security/nss/lib/certdb/pcertdb.c lock over the entire search: for small linked listed, queues, or arrays, you can lock over the entire search. this strategy is best when lists are short, or even better if lists are relatively read only (they don't change very often) and using reader/writer locks. copy the linked list: instead of operating on t...
...ld be created, and the sec_setkey() function, above, made on that handle. fortunately most of the existing api has the correct semantics. the exception to this global effects rule may be functions which set global state for an application at initialization time. methods/functions design init, shutdown functions if a layer has some global initialization tasks, which need to be completed before the layer can be used, that layer should supply an initialization function of the form layer_init(). if an initialization function is supplied, a corresponding layer_shutdown() function should also be supplied. layer_init() should increment a count of the number of times it is called, and layer_shutdown() should decrement that count, and shutdown when the count reaches '0'. open, close functi...
NSS Developer Tutorial
ine1 ** line2 */ or /* line1 * line2 */ naming public functions are named foo_dooneaction. global, but unexported functions, are usually named foo_dooneaction. variable, and function parameter names, always start with a lowercase letter. the most common style is foobarbaz, although foobarbaz and foo_bar_baz are also used. miscellaneous goto can be used, to simplify resource deallocation, before returning from a function. a data buffer 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 c...
...y nspr in the future). universal character names are not permitted, as are wide character types (char16_t and char32_t). nss source should only include ascii text. escape non-printing characters (with \x if there is no special escape such as \r, \n, and \t) and avoid defining string literals that use non-ascii characters. one line comments starting with // are permitted. check with nss-dev@ before using a language feature not already used, if you are uncertain. please update this list if you do. these restrictions are different for c++ unit tests, which can use most c++11 features. the mozilla c++ language features guide, and the chromium c++ usage guide, list c++ features that are known to be widely available and compatible. you should limit features to those that appear in both guides.
NSS tools : certutil
e a specific scenario. use the -h option to show the complete list of arguments for each command option. creating new security databases certificates, keys, and security modules related to managing certificates are stored in three related databases: * cert8.db or cert9.db * key3.db or key4.db * secmod.db or pkcs11.txt these databases must be created before certificates or keys can be generated. certutil -n -d [sql:]directory creating a certificate request a certificate request contains most or all of the information that is used to generate the final certificate. this request is submitted separately to a certificate authority and is then approved by some mechanism (automatically or by human review). once the request...
...are to give the security database directory and to identify the certificate nickname. certutil -d -d [sql:]directory -n "nickname" for example: $ certutil -d -d sql:/home/my/sharednssdb -n "my-ssl-cert" validating certificates a certificate contains an expiration date in itself, and expired certificates are easily rejected. however, certificates can also be revoked before they hit their expiration date. checking whether a certificate has been revoked requires validating the certificate. validation can also be used to ensure that the certificate is only used for the purposes it was initially issued for. validation is carried out by the -v command option. certutil -v -n certificate-name [-b time] [-e] [-u cert-usage] -d [sql:] directory f...
NSS tools : modutil
disabled with the -enable or -disable options. -string config_string pass a configuration string for the module being added to the database. -tempdir temporary-directory give a directory location where temporary files are created during the installation by the -jar option. if no temporary directory is specified, the current directory is used. usage and examples creating database files before any operations can be performed, there must be a set of security databases available. modutil can be used to create these files. the only required argument is the database that where the databases will be located. modutil -create -dbdir [sql:]directory adding a cryptographic module adding a pkcs #11 module means submitting a supporting library file, enabling its ciphers, and setting defaul...
...e directory relative to which files should be installed; for example, it may be the server's root directory. the %temp% directory is created at the beginning of the installation and destroyed at the end. the purpose of %temp% is to hold executable files (such as setup programs) or files that are used by these programs. files destined for the temporary directory are guaranteed to be in place before any executable file is run; they are not deleted until all executable files have finished. absolutepath specifies the destination directory of the file as an absolute path. executable specifies that the file is to be executed during the course of the installation. typically, this string is used for a setup program provided by a module vendor, such as a self-extracting setup executable. mor...
gtstd.html
started with ssl this chapter describes how to set up your environment, including certificate and key databases. ssl, pkcs #11, and the default security databases setting up the certificate and key databases building nss programs ssl, pkcs #11, and the default security databases the basic relationships among the nss libraries are described in introduction to network security services. before running the sample programs, it's important to understand the relationships between the ssl interface, the pkcs #11 interface, pkcs #11 modules, and the default netscape security databases. a pkcs #11 module (also called a cryptographic module) manages cryptographic services such as encryption and decryption via the pkcs #11 interface. pkcs #11 modules can be thought of as drivers for cryptograp...
...ility that comes with nss, to manage pkcs #11 module information within secmod.db files. the security module database tool allows you to add and delete pkcs #11 modules, change passwords, set defaults, list module contents, enable or disable slots, enable or disable fips-140-1 compliance, and assign default providers for cryptographic operations. setting up the certificate and key databases before you can run the sample programs (server.c and client.c) that come with nss, you must set up certificate, key, and security module databases for both the client and the server and populate them with valid ca, client ssl, and server ssl certificates. the following sections decribe how to the certificate database tool to perform these tasks: setting up the ca db and certificate setting up the ser...
NSS Tools certutil
if a ca key pair is not available, you can create a self-signed certificate (for purposes of illustration) with the -x argument. this example creates a new binary, self-signed ...
...tificate in the database with this command: certutil -l -n jsmith@netscape.com -d certdir the certificate database tool displays output similar to the following: certificate: data: version: 3 (0x2) serial number: 0 (0x0) signature algorithm: pkcs #1 md5 with rsa encryption issuer: cn=john smith, o=netscape, l=mountain view, st=california, c=us validity: not before: thu mar 12 00:10:40 1998 not after: sat sep 12 00:10:40 1998 subject: cn=john smith, o=netscape, l=mountain view, st=california, c=us subject public key info: public key algorithm: pkcs #1 rsa encryption rsa public key: modulus: 00:da:53:23:58:00:91:6a:d1:a2:39:26:2f:06:3a: 38:eb:d4:c1:54:a3:62:00:b9:f0:7f:d6:00:76:aa: 18:da:6b:79:71:5b:d9:8a:82:...
certutil
to illustrate a specific scenario. use the -h option to show the complete list of arguments for each command option. creating new security databases certificates, keys, and security modules related to managing certificates are stored in three related databases: o cert8.db or cert9.db o key3.db or key4.db o secmod.db or pkcs11.txt these databases must be created before certificates or keys can be generated. certutil -n -d [sql:]directory creating a certificate request a certificate request contains most or all of the information that is used to generate the final certificate. this request is submitted separately to a certificate authority and is then approved by some mechanism (automatically or by human review). once the request is approve...
...ptions are to give the security database directory and to identify the certificate nickname. certutil -d -d [sql:]directory -n "nickname" for example: $ certutil -d -d sql:/home/my/sharednssdb -n "my-ssl-cert" validating certificates a certificate contains an expiration date in itself, and expired certificates are easily rejected. however, certificates can also be revoked before they hit their expiration date. checking whether a certificate has been revoked requires validating the certificate. validation can also be used to ensure that the certificate is only used for the purposes it was initially issued for. validation is carried out by the -v command option. certutil -v -n certificate-name [-b time] [-e] [-u cert-usage] -d [sql:]directory for example,...
NSS tools : modutil
Mozilla › Projects › NSS › tools › modutil
fig_string pass a configuration string for the module being added to the database. -tempdir temporary-directory give a directory location where temporary files are created during the installation by the -jar option. if no temporary directory is specified, the current directory is used. usage and examples creating database files before any operations can be performed, there must be a set of security databases available. modutil can be used to create these files. the only required argument is the database that where the databases will be located. modutil -create -dbdir [sql:]directory adding a cryptographic module adding a pkcs #11 module means submitting a supporting library file, enabling its ciphers, and...
...ry relative to which files should be installed; for example, it may be the server's root directory. the %temp% directory is created at the beginning of the installation and destroyed at the end. the purpose of %temp% is to hold executable files (such as setup programs) or files that are used by these programs. files destined for the temporary directory are guaranteed to be in place before any executable file is run; they are not deleted until all executable files have finished. absolutepath specifies the destination directory of the file as an absolute path. executable specifies that the file is to be executed during the course of the installation. typically, this string is used for a setup program provided by a module vendor, such as a self-extracting setup ex...
Multithreading in Necko
ot worry about threading issues. the internal i/o interfaces default to proxying all callbacks to the main thread. this keeps simple protocol handlers simple :-) more complex protocol handlers (eg. http, ftp) operate partially on the background threads to improve performance. for example, the http protocol handler has code that runs on the socket transport thread to kick off pending requests well before the main thread would get around to doing so. socket transport thread (1) socket connections are processed on a single background thread. this thread is controlled by the nssockettransportservice. it sits in a loop, polling a list of sockets. when a socket can be read, the socket's listener is notified either synchronously (on the same thread) or asynchronously via a nsistreamlistenerproxy imp...
...ach file transport object is given time on one of the file transport threads. during which it reads (writes) until its buffers are full (empty). once at the limit of its buffers, it yields the thread to another pending file transport object. as with the socket transport thread, the nsistreamlistener passed to a file transport's asyncread method can operate partially on the file transport's thread before proxying data to the main thread. the file transport is confusingly named since it is not restricted to loading files. it simply promises to read from a nsiinputstream (or write to a nsioutputstream) on a background thread. the implementation of the stream should be blocking; however, there is limited support for non-blocking streams. cached page loads, file url loads, and jar url loads all utili...
Rhino overview
however, rhino is an implementation of the core language only and doesn't contain objects or methods for manipulating html documents. rhino contains all the features of javascript 1.7 allows direct scripting of java a javascript shell for executing javascript scripts a javascript compiler to transform javascript source files into java class files a javascript debugger for scripts executed with rhino language the javascript language itself is standardized by standard ecma-262 ecmascript: a general purpose, cross-platform programming language. rhino 1.3 and greater conform to edition 3 of the standard. ...
... attribute of the script tag with values such as "javascript1.2". version 1.3 and greater are ecma conformant. operators == and != version 1.2 only uses strict equality for the == and != operators. in version 1.3 and greater, == and != have the same meanings as ecma. the operators === and !== use strict equality in all versions. toboolean boolean(new boolean(false)) is false for all versions before 1.3. it is true (and thus ecma conformant) for version 1.3 and greater. array.prototype.tostring and object.prototype.tostring version 1.2 only returns array or object literal notation ("[1]" or "{a:1, b:2}" for example). in version 1.3 and greater these functions are ecma conformant. array constructor array(i) for a number argument i constructs an array with a single element equal to i for v...
Rhino scopes and contexts
both are required to execute scripts, but they play different roles. simple embeddings of rhino probably won't need any of the information here, but more complicated embeddings can gain performance and flexibility from the techniques described below. contexts the rhino context object is used to store thread-specific information about the execution environment. there should be one and only one context associated with each thread that will be executing javascript. ...
...e adds to the sealed shared scope since although after calling sealedsharedscope.sealobject(); it would no be possible to set the additional properties to different values, one still would be able to alter the objects themselves. note that currently in order to use java classes (liveconnect) from a sealed shared scope you need to pre-load a number of objects needed for liveconnect into the scope before it gets sealed. these objects would normally be lazy loaded but the lazy loading fails if the scope is sealed. scriptableobject sealedsharedscope = cx.initstandardobjects(null, true); // force the liveconnect stuff to be loaded. string loadme = "regexp; getclass; java; packages; javaadapter;"; cx.evaluatestring(sealedsharedscope , loadme, "lazyload", 0, null); sealedsharedscope .sealobject(); ...
SpiderMonkey Build Documentation
when building a version older than 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. ...
...unning: ./jit-test/jit_test.py ${builddir}/dist/bin/js building spidermonkey 1.8 or earlier use these instructions to build spidermonkey from an official source release or from the old cvs repository. to build the latest spidermonkey sources from mercurial, see building spidermonkey above. spidermonkey is easy to build from source if you have the usual mozilla build prerequisites installed. before you begin, make sure you have right build tools for your computer: linux, windows, mac, others. first, download a spidermonkey source distribution, such as spidermonkey 1.8 release candidate 1. to build, use these commands: tar xvzf js-1.8.0-rc1.tar.gz cd js/src make -f makefile.ref this builds a debug version of spidermonkey. all build files are created in a subdirectory named depending on ...
Creating JavaScript tests
between the two test suites: jstest new jstest files should be put the code in the appropriate subdirectory of js/src/tests/non262/, or, under some scenarios, contributed directly to the test262 repository. jstests run in both the shell and the browser (although you can specify that the test should be run in only one of the two locations). jstests automatically load js/src/tests/shell.js before they run, which creates a ton of functions. read more advice on jstests here. jit-test new jit-test files should be put in js/src/jit-test/tests/basic or one of the other appropriate subdirectories of jit-test/tests. jit-tests run only in the shell. jit-tests do not load extra test functionality automatically. writing a new test file have a look at the existing files and follow what t...
...nge is performance sensitive is on arewefastyet.com. focus on writing fast, light tests that cover a single feature. there is basically no cost to adding a new test, so add as many feature tests as needed to cover each feature orthogonally. remember that whenever a test fails, someone -- probably you -- is going to have to figure out what went wrong. testing your test run your new test locally before checking it in (or posting it for review). nobody likes patches that include failing tests! see running automated javascript tests for instructions on how to run jstests or jit-tests. it's also a good sanity check to run each new test against an unpatched shell or browser. the test should fail if it's working properly. checking in completed tests tests are usually reviewed and pushed just lik...
GCIntegration - SpiderMonkey Redirect 1
of: interactions between the garbage collector and the cycle collector incremental garbage collection moving garbage collection the apis for gc/cc interaction and incremental gc are already in place. development of moving gc (both generational and compacting) is under way, but only in the javascript shell so far. we're still thinking about how the apis for moving gc should work. overview before digging too deep, here are some quick rules of thumb for how to write code that will work smoothly with the gc regardless of changes that happen in the future. avoid having c++ objects that point to js objects (unless it's just to their own wrapper--that's okay). it's safe for js objects to point to other js objects or to c++ objects. if there is a choice between storing a gc thing inside a c+...
... gecko are traced via ns_decl_cycle_collection_script_holder_class and its related macros. these pointers are always traced in the first slice, and so they don't need a write barrier. many other xpconnect pointers are also traced in this way. see xpcjsruntime::traceblackjs and xpcjsruntime::tracegrayjs. if a pointer doesn't fit one of these categories, then it probably requires a write barrier. before the pointer is modified (except initializing writes, which don't need a barrier), you should call incrementalreferencebarrier() or incrementalvaluebarrier(), passing it the value the pointer held before the write. there are several examples of this usage in xpconnect. the js::objectptr class is intended to serve as a drop-in replacement for jsobject *. it has an assignment operator that automati...
GC Rooting Guide
rror) valueout.set(resultvalue); return waserror; } void otherfunction(jscontext *cx) { js::rootedvalue value(cx); bool success = maybegetvalue(cx, &value); // ... } return values it's ok to return raw pointers! these do not need to be wrapped in any of rooting classes, but they should be immediately used to initialize a js::rooted<t> if there is any code that could gc before the end of the containing function; a raw pointer must never be stored on the stack during a gc. one rare but especially tricky case to watch out for is where an raii destructor could gc in a function that is returning a bare pointer. consider: jsobject* somefunction(jscontext* cx) { js::rooted<jsobject*> obj(cx, foo()); eventlogger logger(cx); ...code... return obj; } say tha...
...use whichever better fits your situation: void somefunction(jscontext* cx, js::mutablehandleobject obj) { eventlogger(cx); ...code... obj.set(foo()); } (note that the above should probably check the return value and propagate an error on null), or: jsobject* somefunction(jscontext* cx) { js::rooted<jsobject*> obj(cx, foo()); { // make a scope to force the destructor to run before obj is unwrapped. eventlogger(cx); ...code... } return obj; } autorooters gc thing pointers that appear as part of a stack-allocated aggregates (array, structure, class, union) should use js::rooted<t> when possible. there are some situations when using js::rooted<t> is not possible, or is undesirable for performance reasons. to cover these cases, there are various au...
Exact Stack Rooting
things like scope chain objects, which aren't explicitly rooted themselves, but are always reachable from the implicit stack roots. every use of these should be commented to explain why they are guaranteed to be rooted. js::handle<t> typedef js::handle<t> js::handlet; -> handleobject, handlestring, handlescript, etc. any single gcthing is likely to get passed through a fairly deep call-stack before getting used. even though creating a new js::rootedt is cheap, it is silly to repeat this work for every new call frame. to solve this, we use the standard "handle" approach. a js::handlet is a pointer to a js::rootedt. a js::rootedt will automatically convert to a js::handlet. by using js::handlet in the interface instead of direct gcpointers, we ensure that the gcthing is already rooted on some...
...t) { out.set(js_newstringcopyz(cx, "foo")); return bool(out); } size_t getlengthfoo(jscontext *cx) { rootedstring s(cx); if (returnfoo(cx, &s)) return js_getstringlength(s); return size_t(-1); } all methods in the js-api that return gcpointers have been changed to this out-param style. this prevents an entire class of bugs where return values are not rooted properly before the next js-api call. js::nullptr null (or nullptr) does not implicitly convert to a js::handlet. for places where you want to pass a null value into a function taking a js::handlet, you can construct and pass a new nullptr instance. you are free to use these as temporaries. rootedobject obj(cx, js_newobject(cx, clasp, nullptr(), nullptr()); common pitfalls the c++ type system allows us to ...
JIT Optimization Strategies
o a property on the global object. getprop_typedobject optimizes accesses to properties on typedobjects. getprop_definiteslot optimizes access to a well-known regular property on an object. for this optimization to succeed, the property needs to be well-defined on the object. for objects constructed by constructor functions, this means that the property needs to be defined in the constructor, before any complex logic occurs within the constructor. this is the best case for a regular "field" type property that is not turned into a constant. it compiles down to a single cpu-level load instruction. function someconstructor() { this.x = 10; // x is a definite slot property this.y = 10; // y is a definite slot property somecomplicatedfunctioncall(); this.z = 20; // z is...
...s objects as well as dom objects. setprop_typedobject optimizes accesses to properties on typedobjects. setprop_definiteslot optimizes a write to a well-known regular property on an object. for this optimization to succeed, the property needs to be well-defined on the object. for objects constructed by constructor functions, this means that the property needs to be defined in the constructor, before any complex logic occurs within the constructor. this is the best case for a regular "field" type property that is not turned into a constant. it compiles down to a single cpu-level load instruction. function someconstructor() { this.x = 10; // x is a definite slot property this.y = 10; // y is a definite slot property somecomplicatedfunctioncall(); this.z = 20; // z is...
JSAutoByteString
techarstonewlatin1charsz, or allocate string and copy the content of jslinearstring::latin1chars, and take the ownership of the string. this may fail if str is not linear. char *encodeutf8(jscontext *cx, js::handlestring str) call js_encodestringtoutf8 and take ownership of the returned string, and return the string. void clear() free the owned string. you should call this before calling encode* methods or initbytes method if a string is already owned, otherwise the string will never be freed. char *ptr() const return a pointer to the owned string. this could be null if no string is owned. bool operator!() const return true if no string is owned. size_t length() const return the length of the owned string. return 0 if no string is owned...
...tr); style, it calls js_encodestring(cx, str) to get the string to take ownership. if jsautobytestring instance is initialized with jsautobytestring bytes; style, it does not own any string. you can call some methods to take ownership of other string. note that the js_encodestring call in constructor and some encode* methods may fail and get null. so ensure the string is returned by operator!() before using ptr() method. examples use constructor arguments { jsstring *str = js::tostring(cx, strval); if (!str) return false; jsautobytestring bytes(cx, str); /* calls js_encodestring internally */ if (!bytes) return false; /* ...do something with bytes... */ /* when leaving this scope, the string returned by js_encodestring is freed. */ } use method to encode string { ...
JSNewEnumerateOp
op adds to the properties vector are added to the set of values the for-in loop will iterate over. all of this is nonstandard. an object is "enumerated" when it's the target of a for-in loop or js_enumerate. all other property inspection, including object.keys(obj), goes through [[ownkeys]]. the callback's job is to populate properties with all property keys that the for-in loop should visit. ...
...(you can use private_to_jsval to tag the pointer to be stored). ...
JS_GetGCParameter
jsgc_max_nursery_bytes / "maxnurserybytes" maximum size the nursery may grow to, or 0 to disable generational gc. jsgc_min_nursery_bytes / "minnurserybytes" minimum size the nursery may shrink to. jsgc_bytes / "gcbytes" amount of bytes allocated b...
...ure_threshold, jsgc_pretenure_group_threshold, jsgc_nursery_free_threshold_for_idle_collection_percent, jsgc_min_nursery_bytes, jsgc_min_last_ditch_gc_period, } jsgcparamkey; value (c++/js shell) description jsgc_max_bytes / "maxbytes" maximum nominal heap before last ditch gc. jsgc_max_malloc_bytes / "maxmallocbytes" number of js_malloc bytes before last ditch gc. jsgc_max_nursery_bytes / "maxnurserybytes" maximum size the nursery may grow to, or 0 to disable generational gc. jsgc_min_nursery_bytes / "minnurserybytes" minimum size the nursery may shrink to. jsgc_bytes / "gcbytes" amount of bytes allocated by the gc. jsgc_number / "gcnumber" number of times gc has been invoked. includes both maj...
JS_NewGlobalObject
registered via the debugger api. these callbacks are arbitrary script, and can touch the global in arbitrary ways. when that happens, the global should not be in a half-baked state. but this creates a problem for consumers that need to set slots on the global to put it in a consistent state. this api provides a way for consumers to set slots atomically (immediately after the global is created), before any debugger hooks are fired. it's unfortunately on the clunky side, but that's the way the cookie crumbles. if callers have no additional state on the global to set up, they may pass fireonnewglobalhook to js_newglobalobject, which causes that function to fire the hook as its final act before returning. otherwise, callers should pass dontfireonnewglobalhook, which means that they are responsibl...
...this lets us be sure that debugger clients never miss breakpoints. ...
JS_SetGCCallback
in the order listed. sometimes jsgc_begin happens and the rest of garbage collection does not happen, so the other three callbacks are not called. sometimes several gc cycles happen in a row, so jsgc_begin is followed by alternating jsgc_mark_end and jsgc_finalize_end callbacks, followed at last by jsgc_end. the jsgc_begin callback can occur very early when something triggers garbage collection—before the javascript engine has even determined whether gc should actually be done at the moment. some quirky behavior follows from this: the javascript engine can call the gc callback reentrantly on a single thread. for example, if the jsgc_mark_end callback does something that triggers gc, a jsgc_begin callback might happen. but the javascript engine will then detect that gc is already happening an...
...hreadsafe build, a jsgc_begin callback may happen on any thread, any time that thread triggers garbage collection (from almost any jsapi call). the gc callback may be called on multiple threads at the same time (e.g. if a thread that is not in an active request calls js_gc while gc is already happening on another thread). in a js_threadsafe build, a jsgc_begin callback can happen on one thread before or while a jsgc_end callback for the previous gc cycle runs on another thread. in a js_threadsafe build, the jsgc_end callback is called after each stop-the-world rendezvous during which one or more garbage collection cycles finished. the callback executes on the same thread that performed gc, after the gc lock has been released. other threads may be running in active requests. see also mxr id...
JS_THREADSAFE
cx); read_size = recv(socket, buf, size, flags); js_resumerequest(cx, rc); ... } garbage collection requests help make garbage collection safe when multiple threads are using the jsapi. for each thread that is in a request: almost any call into the jsapi may trigger garbage collection; but garbage collection does not happen at any other time (such as, for example, at the moment before the return value of js_newobject is assigned to a rooted variable). these are actually the same rules that apply to single-threaded jsapi programs. but in multithreaded programs, if you break the rules, your program is more likely to crash. this is because in single-threaded programs, a random call into the jsapi is actually pretty unlikely to trigger gc, especially if the calling thread has no...
...if the calling thread has been idle, other threads may be active or may call js_gc(). the above rules mean that at any given moment, there can be either (a) multiple threads in active requests, or (b) one thread doing gc and all requests suspended. when one thread calls js_gc or otherwise finds that garbage collection is necessary, it must wait for all other threads that are in requests to pause before garbage collection can occur. to keep this wait time to a minimum, applications must avoid long-running requests. the recommended technique in spidermonkey 1.8 and later is to periodically call js_yieldrequest from an operation callback. sharing data among threads "data can be marshaled across the process boundary through a process known as smuggling." --mr. bunny's guide to activex even in js...
Thread Sanitizer
--disable-debug starting the build process now you start the build process using the regular make -f client.mk command. starting firefox after the build has completed, you can start firefox from the objdir as usual. building only the javascript shell if you want to build only the javascript shell instead of doing a full firefox build, the build script below will probably help you to do so. before using it, you must of course adjust the path name for llvm_root to match your setup. once you have adjusted everything, execute this script in the js/src/ subdirectory and pass a directory name as the first parameter. the build will then be created in a new subdirectory with that name. #! /bin/sh if [ -z $1 ] ; then echo "usage: $0 <dirname>" elif [ -d $1 ] ; then echo "directory $1 alr...
...er 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=/path/to/llvm-symbolizer" before running the process. if you've built tsan as described above, then you will want to set the variable to $llvm_home/build/bin/llvm-symbolizer. ignoring known races in some cases, races can be confirmed to be benign and fixing them would cause possible performance issues. tsan offers two possibilities to ignore such known races. compile-time blacklisting functions with racy memory access can be...
Web Replay
ng, as heap allocation is non-deterministic while replaying. mprotect is intercepted and nop'ed to avoid interference with the dirty memory mechanism, and munmap is intercepted with no actual unmapping performed, so that memory does not need to be remapped when restoring a snapshot (a set of free regions is maintained to allow reusing this memory). all snapshots are taken from the main thread. before taking the snapshot, all threads participating in the recording must enter an idle state, waiting on a thread-specific condition variable. threads enter this state whenever they are waiting to acquire a lock or perform an atomic action that is part of the recording. while recording, threads may make blocking calls to libraries (e.g. kevent). to allow these threads to be snapshotted, the call i...
...napshotted, the call is instead performed on a separate thread that does not participate in the recording, so that the calling thread may enter the correct idle state even while its progress is blocked on the call completing. once all thread are idle, the main thread computes the memory diff, reads the stacks from each thread and their register state (which each thread recorded by calling setjmp before idling). restoring snapshots is also done from the main thread. as for taking a snapshot, all other threads enter an idle state. the dirty memory information computed since the last snapshot was taken is used to restore the heap to the state at that last snapshot, and then the memory diffs can be used to restore an earlier snapshot if necessary. threads are individually responsible for restor...
Exploitable crashes
can't be as certain as in the case where you see a bogus address at the top of the stack in step 1. finding exploitable crashes exploitable crashes are most often discovered through normal testing and usage, when developers recognize a crash stack in gdb or submitted to a bug as exploitable. additionally, mozilla developers make heavy use of two tools in particular to find exploitable situations before they show up as exploitable crash reports. the first tool is addresssanitizer (asan). there is an mdn article documenting its use with mozilla projects. the other tool is valgrind. there is an mdn article documenting its use with mozilla projects. next steps once you've determined that a crash is potentially exploitable, take the following steps. if you need help with any of the steps (e.g. perha...
...nting its use with mozilla projects. next steps once you've determined that a crash is potentially exploitable, take the following steps. if you need help with any of the steps (e.g. perhaps you lack necessary bugzilla privileges) please email security@mozilla.org. make sure a bug is on file. mark the bug as security-sensitive by putting it into the "security-sensitive core bug" group. do this before making comments or taking actions that expose exploitability publicly. put a security severity rating in the bug's keywords. if you're not sure what rating to give, err on the higher side so the bug will get more attention. explain in a comment why the issue seems exploitable. other tools apple has a tool called "crashwrangler" that are still being maintained as of 2012. there is little public...
Setting up an update server
done. also, the mozilla maintenance service is only used if the install directory is within c:\program files or c:\program files (x86), so make sure your install directory is in one of those locations. now that you have a build of firefox capable of using a locally-built mar, it's time to build the mar. first, build firefox the way you want it to be after updating. if you want it to be the same before and after updating, this step is unnecessary and you can use the same build that you used to create the installation. then run these commands, substituting <obj dir>, <mar output path>, <version> and <channel> appropriately: ./mach package touch "<obj dir>/dist/firefox/precomplete" mar="<obj dir>/dist/host/bin/mar.exe" moz_product_version=<version> mar_channel_id=<channel> ./tools/update-packagi...
...as when you paste this number into the xml file. on macos, you can get the exact size of your mar by running the command: stat -f%z <filename> or on linux, the same command would be: stat --format "%s" <filename> starting your update server now, start an update server to serve the update files on port 8000. an easy way to do this is with python. remember to navigate to the correct directory before starting the server. this is the python2 command: python -m simplehttpserver 8000 or, this is the python3 command: python3 -m http.server 8000 if you aren't sure that you started the server correctly, try using a web browser to navigate to http://127.0.0.1:8000/update.xml and make sure that you get the xml file you created earlier. installing the update you may want to start by deleting a...
Gecko object attributes
elative to the top of the currently focused area (the document, a rich text editable area, or an input control). applied to: any focusable accessible text object margin-bottom specifies how much vertical space there will be after the bottom of the last line of content in a text accessible (see the css margin-bottom property). ...
...operty). margin-left specifies how much horizontal space there will be before the beginning of each line of content in a text accessible (see the css margin-left property). margin-right specifies how much horizontal space there will be after the end of each line of content in a text accessible (see the css margin-right property). margin-top specifies how much vertical space there will be before the top of the first line of content in a text accessible (see the css margin-top property). text-align specifies how lines of text are aligned with each other (see css text-align property). text-indent specifies how much horizontal space should be left before beginning of the first line of the text content of an text accessible (see the css text-indent property). value attributes valuet...
Mork
Mozilla › Tech › Mork
of a row or rowreference in the meta-table indicates that said row is the meta-row of the table: it contains arbitrary properties for the entire table just like a normal row. for example, the message summary format files use a table for each thread, where the meta-rows represent information about the thread in general. the last important point about tables is the meaning of the minuses. a minus before the table id indicates that all the rows currently stored in the table should be removed before adding more rows. a minus sign before a row or rowreference indicates that said row should be removed from the table. rows for the most part, a row should not be seen outside of a table; the only time i have seen one outside a table is for table meta-rows. the first mid, as you should expect by now, is...
...mportant part of the id, in that 1:scope1 is not the same row as 1:scope2. if the scope is not specified, then it is the default scope of the table (if it has one) or 'r' otherwise. these row ids are global, even if defined in a table. indeed, defining a row in a table is a shortcut for both defining a row and adding the row to the table. the presence of an initial minus means to delete all cells before adding new cells. a minus after the mid indicates that the next cell should be deleted. i haven't seen that case though, so it may not be an issue in practice. the rowreference is a mid that refers to a specific row. if it occurs in a table, you can treat it as adding that row to a table; in a meta-table, it is the same as making that row the meta-row of the table. groups, a.k.a. changesets a gro...
Places Expiration
ing performances when there is no need for it. apart this periodic expiration, there are other steps on idle, on shutdown on clear history. on idle on idle it expires a larger chunk of pages, then timed expiration is stopped. this ensures to not interfere with standby tasks and preserves battery on mobile. on shutdown most of the times the adaptive algorithm will ensure the database is clean before shutdown, so the only task executed on shutdown will be removal of session data (like session annotations). in some cases, like when a clear history is executed just before shutdown, a larger step is executed instead. on maintenance when places maintenance runs (about once a week, on daily idle), an orphans expiration step is executed, this ensures database cleanup. preferences usually there ...
...o need to tweak or set any preference, since adaptive behavior should satisfy each need, though in case of unexpected issues it's possible to act on some hidden preferences: places.history.expiration.interval_seconds: minimum number of seconds between expiration steps. default is 180 seconds. places.history.expiration.max_pages: the maximum number of pages that may be retained in the database before starting to expire. default value is calculated on startup and put into the places.history.expiration.transient_current_max_pages preference. this transient version of the preference is just mirroring the current value used by expiration, setting it won't have any effect. ...
Places utilities for JavaScript
erties: name, flags, expires, type, mimetype (only used for binary annotations) value. other other functions that i'm not sure how to file. getviewfornode() returns the closet ancestor places view for the given dom node getviewfornode(anode) parameters anode a dom node return type return the closet ancestor places view if exists, null otherwsie. markpageastyped() by calling this before we visit a url, we will use transition_typed as the transition for the visit to that url (if we don't have a referrer). this is used when visiting pages from the history menu, history sidebar, url bar, url autocomplete results, and history searches from the places organizer. if we don't call this, we'll treat those visits as transition_link. markpageastyped(string aurl) markpageasfollowedbook...
... use transition_typed as the transition for the visit to that url (if we don't have a referrer). this is used when visiting pages from the history menu, history sidebar, url bar, url autocomplete results, and history searches from the places organizer. if we don't call this, we'll treat those visits as transition_link. markpageastyped(string aurl) markpageasfollowedbookmark() by calling this before we visit a url, we will use transition_bookmark as the transition for the visit to that url (if we don't have a referrer). this is used when visiting pages from the bookmarks menu, personal toolbar, and bookmarks from within the places organizer. if we don't call this, we'll treat those visits as transition_link. markpageasfollowedbookmark(string aurl) checkurlsecurity() allows opening of ja...
The Publicity Stream API
ains 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 arguments are present. getpublicitystream( onsuccess: <function>, { [ onerror: <function> ], [ for_apps: <list> ], [ since: <date> ], [ before: <date> ], [ count: <int> ]): provides a means for a web store to receive a list of the current user's socially relevant app activity by being called from an origin which hosts a web store. it is not recommended that applications consume the publicity stream in any way (please use your own server for any in-app social aspects). it is suggested that the list be processed and condensed into an at...
...s 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 of the earliest event you want returned. if not specified, will default to the beginning of the stream. before the timestamp of the latest event you want returned. if not specified, will default to now. count the maximum number of events to return, with preference given to more recent events [make this preference its own parameter?]. if not specified, will default to [25]. ...
Aggregating the In-Memory Datasource
nted to trap flush() so that i could write the bookmarks.html file back to disk. in short, the only case where this technique is useful is when you're implementing a datasource to get "read-only reflection". that is, you want to reflect the contents of something as an rdf graph (presumably so that it can be aggregated with other information or displayed as styled content). technical details as before, have an nscomptr as your delegate, but this time around,don't derive from nsirdfdatasource. also, instead of keeping an nscomptr<nsirdfdatasource>, you'll just want an nscomptr<nsisupports>: class myclass : public nsimyinterface { ... private: nscomptr<nsisupports> minner; }; construct the datasource delegate when your object is constructed (or, at worst, when somebody qi's for it): ...
...for example: ns_imethodimp myclass::dosomething() { nscomptr<nsirdfdatasopurce> ds = do_queryinterface(minner); rv = ds->assert(/* something useful here */); // etc... return ns_ok; } it may be tempting to keep a pointer to the aggregate's nsirdfdatasource in a member variable, butyou can't do that. why...
An Overview of XPCOM
as a dynamic_cast<>, which throws an exception if the shape object is not able to be cast to a circle. but enabling exceptions and rtti may not be an option because of performance overhead and compatibility on many platforms, so xpcom does things differently. exceptions in xpcom c++ exceptions are not supported directly by xpcom. instead all exceptions must be handled within a given component, before crossing interface boundaries. in xpcom, all interface methods should return an nsresult error value (see the xpcom api reference for a listing of these error codes). these error code results become the "exceptions" that xpcom handles. instead of leveraging c++ rtti, xpcom uses the special queryinterface method that casts the object to the right interface if that interface is supported. every ...
...egrettable, but required for com compliance. ns_import forces the method to be resolved internally by the shared library. ns_export forces the method to be exported by the shared library. reference counting these macros manage reference counting. ns_addref calls addref on an nsisupports object. ns_if_addref same as above but checks for null before calling addref. ns_release calls release on an nsisupports object. ns_if_release same as above but check for null before calling release. status codes these macros test status codes. ns_failed return true if the passed status code was a failure. ns_succeeded returns true is the passed status code was a success. variable mappings ...
Building the WebLock UI
g installed in mozilla or another gecko-based browser, then this third section shows you how to create the entry point in the browser for controlling the web locking. if you are planning on deploying the weblock component in some other application, you'll have to devise a different means of access (e.g., native widgetry that instantiates and controls the weblock 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 in...
...in overlays the ordinarily unique id attributes that xul elements use to distinguish themselves are purposely made redundant with ui in the existing browser with which they should be merged. ...
Starting WebLock
from loading. void lock(); void unlock(); this interface does not enforce any policy with respect to how the user enables or disables this feature. this allows maximum flexibility in the implementation. any place in the application can acquire this interface via the service manager and call unlock or lock. for example, the user interface may bring up a dialog asking the user for a password before calling unlock. another area of code, such as a "profile manager" that starts up and lets users choose which profile to use, may unconditionally call unlock on such a component when switching a profile. the next set of functionality manages the white list where acceptable domains are stored: void addsite(in string url); void removesite(in string url); attribute nsisimpleenumerator sites; ...
...(nsisupportscstring), (void**)&stringsupports); if (!stringsupports) return ns_error_unexpected; nsembedcstring str(mnode->urlstring); stringsupports->setdata(str); *aresult = stringsupports; // addref'ed above. mnode = mnode->next; return ns_ok; } in the actual getsites call, all you have to do is create an instance of myenumerator and return it. before, we created a class and registered it with the component manager. when a client outside of the code wanted to acquire the implementation of an interface, the actual object creation was hidden in the xpcom code. here, however, you instantiate your own implementation of a nsisimpleenumerator. this is a simple thing to do, but it requires that you pay special attention to the ns_addref. ns_imethodi...
Using XPCOM Utilities to Make Things Easier
mount of time when you're writing the code, it can also save time if you make changes to your idl file, since the c++ header file will then automatically include the updated list of methods to be supported. the ns_init_isupports macro is also a bit of a special case. historically, it gets called in the constructor for your class and sets mrefcnt to zero. however, a change in xpcom that occurred before mozilla 1.3 makes ns_init_isupports no longer necessary: mrefcnt's type has been changed from an integer to a class that provides its own auto-initialization. if you are building with versions earlier than mozilla 1.3, this macro is still required. the following table summarizes the macro usage in this portion of the weblock.cpp source file: common xpcom macros ns_impl_isupportsn ...
...a reference by not releasing an object, as the code below demonstrates, can be a major problem. { nsisupports* value = nsnull; object->method(&value); if (!value) return; // ... if (ns_failed(error)) return; // <------------ leaks |value| //... ns_release(value); // release our reference } a method returns an nsisupports interface pointer that has been reference counted before it is returned (assuming it wasn't nsnull). if you handle an error condition by returning prematurely, whatever value points at will leak-it will never be deleted. this is a trivial fix in this example, but in real code, this can easily happen in goto constructs, or in deep nesting with early returns. having more than one interface pointer that needs to be released when a block goes out of scope...
imgIContainer
on will be thrown. read only. constants constant value description type_raster 0 enumerated values for the 'type' attribute (below). type_vector 1 flag_none 0x0 flags for imgicontainer operations. meanings: flag_none: lack of flags. flag_sync_decode: forces synchronous/non-progressive decode of all available data before the call returns. it is an error to pass this flag from a call stack that originates in a decoder (that is, from a decoder observer event). flag_decode_no_premultiply_alpha: do not premultiply alpha if it is not already premultiplied in the image data. flag_decode_no_colorspace_conversion: do not do any colorspace conversion; ignore any embedded profiles, and do not convert to any particu...
...s it is used for ensuring that a valid value was passed in. frame_current 1 frame_max_value 1 knormalanimmode 0 animation mode constants 0 = normal 1 = do not animate 2 = loop once. kdontanimmode 1 klooponceanimmode 2 kdisposeclearall -1 "disposal" method indicates how the image should be handled before the subsequent image is displayed. do not change these without looking at the implementations using them, struct gif_struct::disposal_method and gif_write() in particular. clear() the whole image, revealing. obsolete since gecko 2.0 kdisposenotspecified 0 leave frame, let new frame draw() on top. obsolete since gecko 2.0 kdisposekeep 1 leave frame, let new fram...
imgILoader
to put the image load into. aobserver the observer (may be null) acx some random data. aloadflags load flags for the request. cachekey arequest a newly created, unused imgirequest object or null for one to be created for you. libpr0n does not keep a strong ref to the observer; this prevents reference cycles. this means that callers of loadimage should make sure to cancel() the resulting request before the observer goes away. channelpolicy return value loadimagewithchannel() start the load and decode of an image. libpr0n does not keep a strong ref to the observer; this prevents reference cycles. this means that callers of loadimagewithchannel should make sure to cancel() the resulting request before the observer goes away. imgirequest loadimagewithchannel( in nsichannel achannel, in imgi...
...aobserver the observer (may be null) cx some random data. alistener a listener that you must send the channel's notifications and data to. ...
imgIRequest
ronous, which means that some time after you call it, the listener/observer will get an onstoprequest(). this means that, if you're the observer, you can not call cancel() from your destructor. void cancelandforgetobserver( in nsresult astatus ); parameters astatus clone() clone this request; the returned request will have aobserver as the observer. aobserver will be notified synchronously (before the clone call returns) with all the notifications that have already been dispatched for this image load. imgirequest clone( in imgidecoderobserver aobserver ); parameters aobserver return value decrementanimationconsumers() tell the image it can forget about a request that the image animate. void decrementanimationconsumers(); parameters none. getstaticrequest() if this request is for an...
...ck persists for the lifetime of the imgirequest (until unlockimage() is called) even if the underlying image changes. if you do not call unlockimage() by the time this imgirequest goes away, it will be called for you automatically. void lockimage(); parameters none. requestdecode() requests a decode for the image. imgicontainer has a requestdecode method, but callers may want to request a decode before the container has necessarily been instantiated. calling requestdecode on the imgirequest simply forwards along the request if the container already exists, or calls it once it gets onstartcontainer if the container does not yet exist. void requestdecode(); parameters none. unlockimage() unlocks an image. void unlockimage(); parameters none. ...
mozIStorageConnection
meter. mozistorageconnection clone( in boolean areadonly optional ); parameters areadonly if true, the returned database connection is in read only mode. this is false by default. return value a new mozistorageconnection object representing the cloned connection. exceptions thrown ns_error_unexpected the connection is to a memory database. close() closes a database connection. before closing the connection, you need to finalize all statements created for the connection. note: you must not call this method if any asynchronous statements have been executed on the connection. instead, you should call asyncclose(). void close(); parameters none. exceptions thrown ns_error_unexpected thrown if any statement has been executed asynchronously on the connection, or if the me...
...gresshandler() removes the progress handler that was registered with mozistorageconnection.registerprogresshandler(). mozistorageprogresshandler removeprogresshandler(); parameters none. return value returns the previous registered handler. rollbacktransaction() this method rolls back the current transaction. this is essentially an "undo," and returns the database to the state it was in before the transaction began. void rollbacktransaction(); parameters none. setgrowthincrement() lets you set the amount by which the sqlite database file is grown or shrunk when resizing is necessary. this helps avoid disk fragmentation by letting you help sqlite make intelligent decisions about resizing of the file. note: this works by adjusting the sqlite_fcntl_chunk_size setting in sqlite. v...
nsIAuthPrompt2
nel achannel, in nsiauthpromptcallback acallback, in nsisupports acontext, in pruint32 level, in nsiauthinformation authinfo ); parameters achannel the channel that requires authentication. acallback acontext level one of the level constants. authinfo authentication information object. the implementation should fill in this object with the information entered by the user before returning. return value promptauth() requests a username and a password. implementations will commonly show a dialog with a username and password field, depending on flags also a domain field. note: exceptions thrown from this function will be treated like a return value of false. boolean promptauth( in nsichannel achannel, in pruint32 level, in nsiauthinformation authinfo ); para...
...his function will be treated like a return value of false. boolean promptauth( in nsichannel achannel, in pruint32 level, in nsiauthinformation authinfo ); parameters achannel the channel that requires authentication. level one of the level constants. authinfo authentication information object. the implementation should fill in this object with the information entered by the user before returning. return value false, authentication should be cancelled, usually because the user did not provide username/password. true, authentication can proceed using the values in the authinfo object. see also nsiauthprompt ...
nsIAutoCompleteInput
if true, the text field automatically completes to the default result whenever the user hits the enter key or the text field loses focus. maxrows unsigned long the maximum number of rows to display in the autocomplete suggestion popup. minresultsforpopup unsigned long specifies a minimum number of search results that must be available before the autocomplete popup will open. popup nsiautocompletepopup the view in which results will be displayed.read only. popupopen boolean indicates whether or not the popup view is already open. searchcount unsigned long the number of autocomplete sessions to search. read only. searchparam astrin...
...p, showing the comment for each autocomplete result. showimagecolumn boolean if true, a column is added to the popup, showing an additional image for each autocomplete result. textvalue astring the value of the text in the autocomplete text field. timeout unsigned long the number of milliseconds after a keystroke before a search begins. methods getsearchat() returns the name of one of the autocomplete search session objects. acstring getsearchat( in unsigned long index ); parameters index the index number of the search session object whose name is to be returned. return value the name of the specified object. onsearchbegin() called when the search starts. void onsearchbegin(); parame...
nsICacheEntryDescriptor
isupports get or set the cache data element. this will fail if the cache entry is stream based. the cache entry holds a strong reference to this object. the object will be released when the cache entry is destroyed. file nsifile get the disk file associated with the cache entry. read only. predicteddatasize print64 stores the content-length specified in the http header for this entry. checked before we write to the cache entry, to prevent ever taking up space in the cache for an entry that we know up front is going to have to be evicted anyway. see bug 588507. securityinfo nsisupports get or set security info on the cache entry for this descriptor. this fails if the storage policy is not store_in_memory. storagepolicy nscachestoragepolicy get or set the storage policy of the cache entry...
...ta is a table of key/value string pairs. the strings do not have to conform to any particular charset, but they must be null terminated. string getmetadataelement( in string key ); parameters key the key for retrieving the meta data. return value returns the string value containing the meta data for the provided key. markvalid() this method means that a writer must validate this cache object before any readers are given a descriptor to the object. void markvalid(); parameters none. openinputstream() this method opens blocking input stream to cache data. this will fail if the cache entry is not stream based. use the stream transport service to asynchronously read this stream on a background thread. the returned stream may implement nsiseekablestream. nsiinputstream openinputstream( in uns...
nsICachingChannel
e the cached data can be found. this is valid for as long as a reference to the cache token is held. this may return an error if cacheasfile is false. read only. cacheforofflineuse boolean specifies whether or not the data should be placed in the offline cache, in addition to normal memory/disk caching. this may fail if the offline cache is not present. the value of this attribute should be set before opening the channel. cachekey nsisupports uniquely identifies the data in the cache for this channel. holding a reference to this key does not prevent the cached data from being removed. a cache key retrieved from a particular instance of nsicachingchannel could be set on another instance of nsicachingchannel provided the underlying implementations are compatible and provided the new channel ...
...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 undefined before the channel fires its onstartrequest notification and after the channel fires its onstoprequest notification. see also nsicache ...
nsICompositionStringSynthesizer
s cleared. therefore, you can reuse the instance for modifying composition string. boolean dispatchevent(); return value if dispatched event's default is prevented, returns true. however, this must always return false since all dispatching dom events are not cancelable. setcaret() sets caret position in the composition string set by setstring(). this is optional. i.e., you may not call this before dispatchevent(). void setcaret(in unsigned long aoffset, in unsigned long alength); parameters aoffset caret offset in the composition string. this value must be between 0 and the length of astring of setstring(). alength if you want wide caret, you can set over 0. however, gecko doesn't support wide caret yet. (bug 979112) setstring() sets new composition string. this m...
...(). void setcaret(in unsigned long aoffset, in unsigned long alength); parameters aoffset caret offset in the composition string. this value must be between 0 and the length of astring of setstring(). alength if you want wide caret, you can set over 0. however, gecko doesn't support wide caret yet. (bug 979112) setstring() sets new composition string. this must be called before every call of dispatchevent(). void setstring(in astring astring); parameters astring new composition string. ...
nsICryptoHash
h of the data that was read by this object. this can be either binary data or a base-64 encoded string. exceptions thrown ns_error_not_initialized indicates that init() or initwithstring() has not been called. init() initialize the hashing object. this method may be called multiple times with different algorithm types. note: this method or " .. manch("initwithstring") .. " must be called before any other method on this interface is called. void init( in unsigned long aalgorithm ); parameters aalgorithm the hash algorithm to use. must be one of the hash algorithms. exceptions thrown ns_error_invalid_arg indicates that an unsupported algorithm type was passed initwithstring() initialize the hashing object. this method may be called multiple times with different algorithm...
...ned long aalgorithm ); parameters aalgorithm the hash algorithm to use. must be one of the hash algorithms. exceptions thrown ns_error_invalid_arg indicates that an unsupported algorithm type was passed initwithstring() initialize the hashing object. this method may be called multiple times with different algorithm types. note: this method or " .. manch("init") .. " must be called before any other method on this interface is called. void initwithstring( in acstring aalgorithm ); parameters aalgorithm the hash algorithm type to be used as a string, such as "sha256". exceptions thrown ns_error_invalid_arg indicates that an unsupported algorithm type was passed update() adds an array of data to be hashed to the object. see computing the hash of a string for an exam...
nsIDOMNode
/core/nsidomnode.idlscriptable this interface is the primary datatype for the entire document object model. it represents a single node in the document tree. inherits from: nsisupports last changed in gecko 0.9.6 method overview nsidomnode appendchild(in nsidomnode newchild) nsidomnode clonenode(in boolean deep); boolean hasattributes(); boolean haschildnodes(); nsidomnode insertbefore(in nsidomnode newchild, in nsidomnode refchild) boolean issupported(in domstring feature, in domstring version); void normalize(); nsidomnode removechild(in nsidomnode oldchild) nsidomnode replacechild(in nsidomnode newchild, in nsidomnode oldchild) attributes attribute type description attributes nsidomnamednodemap read only. childnodes nsidomnodelist read only. firstchild ns...
...ent_fragment_node 11 notation_node 12 methods appendchild() nsidomnode appendchild( in nsidomnode newchild ); parameters newchild return value clonenode() nsidomnode clonenode( in boolean deep ); parameters deep return value hasattributes() boolean hasattributes(); parameters none. return value haschildnodes() boolean haschildnodes(); parameters none. return value insertbefore() nsidomnode insertbefore( in nsidomnode newchild, in nsidomnode refchild ); parameters newchild refchild return value issupported() boolean issupported( in domstring feature, in domstring version ); parameters feature version return value normalize() void normalize(); parameters none. removechild() nsidomnode removechild( in nsidomnode oldchild ); parameters oldchild r...
nsIDOMWindowUtils
ber of css pixels to expand the rectangle downward from the point (ax, ay). aleftsize the number of css pixels to expand the rectangle to the left from the point (ax, ay). aignorerootscrollframe whether or not to ignore the root scroll frame when retrieving the nodes. if this is false, this method will return null for coordinates outside the viewport. aflushlayout if true, layout is flushed before hit testing begins. this ensures that the node list is current. if you don't need an absolutely up to date node list, you can set this to false. return value an nsidomnodelist referencing all the nodes that intersect the specified rectangle. processupdates() obsolete since gecko 13.0 (firefox 13.0 / thunderbird 13.0 / seamonkey 2.10) force processing of any queued p...
...long amodifiers, in boolean apreventdefault optional ); obsolete since gecko 15.0 parameters atype event type. akeycode key code. acharcode character code. amodifiers modifiers pressed. using constants defined in nsidomnsevent. obsolete since gecko 15.0 using constants defined as modifier_*. apreventdefault optional obsolete since gecko 15.0 if true, preventdefault() the event before dispatch. aadditionalflags optional 0 or key_flag_prevent_default and/or one of key_flag_location_*. if key_flag_prevent_default is specified, the dispatching key event's default is prevented. if key_flag_location_* isn't set, an appropriate location is automatically computed from akeycode. if two or more key_flag_location_* is specified, this method will throw an exception. return value ...
nsIFileInputStream
eam that allows you to read from a file. 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. close_on_eof 1<<2 if this is set, the file will close automatically when the end of the file is reached. reopen_on_rewind 1<<3 if this is set, the file will b...
...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 would happen during the first read. also, the file is not locked when init is called, so it might be deleted before we try to read from it. methods init() void init( in nsifile file, in long ioflags, in long perm, in long behaviorflags ); parameters file file to read from (must qi to nsilocalfile) ioflags the file status flags define how the file is accessed. see pr_open documentation for more details. if set to -1 the file will be opened in default mode (pr_rdonly). perm file mo...
nsIFilePicker
in effect. defaultextension astring the extension for the type of files you want to work with. on some platforms, this is automatically appended to filenames the user enters, if required. specify it without a leading dot, for example "jpg". defaultstring astring the filename, including extension, that should be suggested to the user as a default. this should be set before calling open() or show(). exceptions thrown ns_error_failure if you try to read this attribute. displaydirectory nsilocalfile the directory that the file picker dialog should initially display. this should be set this before calling open() or show() to specify a starting point. file nsilocalfile the currently selected file or directory. r...
...ndfilters() appends a list of file extension filters, from the predefined list, to the dialog. void appendfilters( in long filtermask ); parameters note: if appendfilters is the first (or only) call to set the file filters the filter with the smallest code will be used as default filter when displaying the nsifilepicker dialog. if you would like to use another you must append it separately before the others you want to go into the drop down list. filtermask a combination of the filters you wish to use. you may or multiple filters together; for example filterall | filterhtml. init() initialize the file picker widget. the file picker is not valid until this method is called. void init( in nsidomwindow parent, in astring title, in short mode ); parameters parent the nsido...
nsIJSON
son, it has been removed in gecko 7.0. jsobject decode( in astring str ); parameters str the json string to decode. return value the original javascript object, reconstructed from the json string. decodetojsval() note: this method may only be used from native code, and provides a way to decode a json string to a jsval for use in your native code. don't forget to gcroot the result before using it. jsval decodetojsval( in astring str, in jscontext cx ); parameters str the json string to decode. cx the javascript runtime context to use to decode the string. return value the original javascript object, reconstructed from the json string. don't forget to gcroot the jsval before using it. decodefromstream() decodes a json string read from an input stream, returni...
... not described. this method is intended for use only by code processing legacy data. when the original instance requiring this function is removed, this method will be removed. thus, this deprecated method should not be used. note: this method may only be used from native code, and provides a way to decode a json string to a jsval for use in your native code. don't forget to gcroot the result before using it. jsval legacydecodetojsval( in astring str, in jscontext cx ); parameters str the json string to decode. cx the javascript runtime context to use to decode the string. return value the original javascript object, reconstructed from the json string. don't forget to gcroot the jsval before using it. see also json ...
nsILoginManagerPrompter
void init(in nsidomwindow awindow); void prompttochangepassword(in nsilogininfo aoldlogin, in nsilogininfo anewlogin); void prompttochangepasswordwithusernames([array, size_is(count)] in nsilogininfo logins, in pruint32 count, in nsilogininfo anewlogin); void prompttosavepassword(in nsilogininfo alogin); methods init() initialize the prompter. must be called before using other interfaces. void init( in nsidomwindow awindow ); parameters awindow the in which the user is doing some login-related action that is resulting in a need to prompt them for something. the prompt will be associated with this window (or, if a notification bar is being used, topmost opener in some cases). prompttochangepassword() ask the user if they want to change a login's ...
...angepasswordwithusernames() ask the user if they want to change the password for one of multiple logins, when the caller can not determine exactly which login should be changed. if the user consents, modifylogin() will be called. note: because the caller does not know the username of the login to be changed, anewlogin.username and anewlogin.usernamefield will be set (using the user's selection) before modifylogin() is called. void prompttochangepasswordwithusernames( [array, size_is(count)] in nsilogininfo logins, in pruint32 count, in nsilogininfo anewlogin ); parameters logins an array of existing logins. count (length of the array) anewlogin the new login. prompttosavepassword() ask the user if they want to save a login (yes, never, not now) void prompttosavepassword( ...
nsIMsgWindow
used to track the character set of the currently displayed message. if set to an alias, the actual character set is returned. charsetoverride boolean remember the message's charset was overridden, so it can be inherited (e.g for quoting). stopped boolean check if a running url been stopped. if you are checking this flag, you need to clear it before you start your operation since there's no convenient place to clear it. domwindow nsidomwindow the message window's global chrome window object. set this to initialize the rootdocshell. methods displayhtmlinmessagepane() loads the specified html in the message pane. this is equivalent to calling loaduri on the nsiwebnavigation object with a data: url specifyin...
...mlinmessagepane(in astring title, in astring body, in boolean clearmsghdr); parameters title not used. body the html to display in the message pane. note that the html is wrapped in <html> and <body> tags for you. clearmsghdr whether or not the existing message pane and header should be cleared before the html is displayed. stopurls() this is equivalent to calling stop(nsiwebnavigation::stop_network) on the nsiwebnavigation object. void stopurls(); closewindow() when the msg window is being unloaded from the content window, this notification can be used to force a flush on anything the message window hangs on. for some reason xpconnect is still hanging onto the message window even though al...
nsINavHistoryService
ll be marked as following a bookmark. void markpageasfollowedbookmark( in nsiuri auri ); parameters auri the page that is to be marked as followed by a bookmark. markpageastyped() this method designates the url as having been explicitly typed in by the user, so it can be used as an autocomplete result. it is called by the url bar when the user types in a url. this can be and is called before the page is actually added to history, since the page isn't added until it actually starts loading. the typed flag affects the url bar autocomplete. this will cause the transition type of the next visit of the url to be marked as "typed." void markpageastyped( in nsiuri auri ); parameters auri the page that is to be marked as typed by the user. markpageasfollowedlink() designates the ...
...rs auri the url that is to be marked as explicitly followed by the user. canadduri() this method checks if the given uri would be added to the history or not. many types of uris, such as "chrome:" uris, are not stored when adduri is called. this function allows you to determine whether it will be or not. you don't have to worry about calling this, addpagetosession/adduri will always check before actually adding the page. this function is public because some components may want to check if this page would go in the history (that is for annotations). boolean canadduri( in nsiuri auri ); parameters auri the uri that needs to be added to the history system. return value returns true if this uri would be added to the history, otherwise returns false. addvisit() o...
nsIPlacesImportExportService
ey 2.11) note: this method has been removed; use the bookmarkhtmlutils.jsm javascript code module instead. loads the given bookmarks.html file and replaces it with the current bookmarks hierarchy (if aisinitialimport is true) or appends it (if aisinitialimport is false). three nsiobserverservice notifications are fired as a result of the import. "bookmarks-restore-begin" is fired just before the import is started. "bookmarks-restore-success" is fired right after the bookmarks are successfully imported. "bookmarks-restore-failed" is fired right after a failure occurs when importing the bookmarks. observers will be passed through their data parameters either "html" if aisinitialimport is false or "html-initial" if aisinitialimport is true. the observer subject will be null. void impor...
...tmlfromfiletofolder() obsolete since gecko 14.0 (firefox 14.0 / thunderbird 14.0 / seamonkey 2.11) note: this method has been removed; use the bookmarkhtmlutils.jsm javascript code module instead.loads the given bookmarks.html file and puts it in the given folder. three nsiobserverservice notifications are fired as a result of the import. "bookmarks-restore-begin" is fired just before the import is started. "bookmarks-restore-success" is fired right after the bookmarks are successfully imported. "bookmarks-restore-failed" is fired right after a failure occurs when importing the bookmarks. observers will be passed through their data parameters either "html" if aisinitialimport is false or "html-initial" if aisinitialimport is true. the observer subject will be an nsisupportspri...
nsIResumableChannel
ed offset. the request given to the nsistreamlistener will be qiable to nsiresumableinfo. void asyncopenat( in nsistreamlistener listener, in nsisupports ctxt, in unsigned long startpos, in nsiresumableentityid entityid ); parameters listener as for asyncopen. ctxt as for asyncopen. startpos the starting offset, in bytes, to use to download. entityid information about the file, to match before obtaining the file. pass an empty string to use anything. resumeat() prepare this channel for resuming. the request will not start until asyncopen or open is called. calling resumeat after open or asyncopen has been called has undefined behaviour. during onstartrequest, this channel will have a status of ns_error_not_resumable if the file cannot be resumed, for example because the server doesn't...
...ch indicates that the entity has changed, as indicated by a changed entityid. in both of these cases, no ondataavailable will be called, and onstoprequest will immediately follow with the same status code. void resumeat( in unsigned long long startpos, in acstring entityid ); parameters startpos the starting offset, in bytes, to use to download. entityid information about the file, to match before obtaining the file. pass an empty string to use anything. see also implementing download resuming ...
nsIScriptableIO
wrapper for other streams. by default, the buffer size is 1024 bytes; however, the size may be changed by specifying the abuffersize parameter. if the text mode is specified, a buffer is always used, regardless of whether or not it is specifically requested. block: when this mode is specified, reading from a transport such as a socket when no data is available will block until data is available before returning. if this mode isn't specified, an exception is thrown if no data is available. deleteonclose: the file is automatically deleted when the stream is closed. this can be useful for temporary files. closeoneof: the file is automatically closed when the end of the file is reached. reopenonrewind: used in conjunction with the seek mode, the file will be reopened when a seek to the begin...
...treams. by default, the buffer size is 1024 bytes; however, the size may be changed by specifying the abuffersize parameter. if the text mode is specified, a buffer is always used, regardless of whether or not it is specifically requested. append: when writing to files, indicates to append to the file rather than overwrite the existing file. the write position will be set to the end of the file before each write. if used in conjuction with the create mode, an existing file may be opened for appending, or a new file created. block: when this mode is specified, writing to a transport such as a socket doesn't return until all data has been written. this may cause a delay if the socket's underlying buffer is full. if you don't specify this mode, an exception is thrown if the buffer is full. no...
nsISound
ened. event_menu_execute 5 a menu item is executed. event_menu_popup 6 a popup menu is shown. event_editor_max_len 7 more characters than the maximum allowed are typed into a text field. methods beep() plays a beep sound. void beep(); parameters none. init() not strictly necessary, but avoids a delay before the first sound. other methods will call init if they need to. void init(); parameters none. play() plays a sound specified by url. void play( in nsiurl aurl ); parameters aurl the url of the sound file to play. playeventsound() plays the system sound for the specified event. if the user's system is configured to not play system sound effects for the event, this will do nothin...
... the name of a system sound provided by the host operating system; for example, if you specify "systemexclamation", you can play the windows alert sound, but it's played only on windows. similarly, if you specify "blow", you can play the mac os x "blow" system sound, but, similarly, it's played only on the macintosh. if you wish to use this method for playing sounds, you should check the platform before you call playsystemsound(). note: this second usage is obsolete starting in gecko 1.9.2. you should instead use playeventsound() instead. typically, it will be more useful to request that appropriate sounds be played based on which event you wish to represent by the sound effect. various event names are provided, which will result in playing the corresponding sound effect on the pl...
nsIStreamListener
nputstream ainputstream, in unsigned long aoffset, in unsigned long acount); methods ondataavailable() this method is called when the next chunk of data for the ongoing request may be read without blocking the calling thread. the data can be read from the nsiinputstream object passed as the argument to this method. note: your implementation of this method must read exactly acount bytes of data before returning. void ondataavailable( in nsirequest arequest, in nsisupports acontext, in nsiinputstream ainputstream, in unsigned long aoffset, in unsigned long acount ); parameters arequest an nsirequest indicating the source of the data. acontext a user-defined context value. ainputstream an nsiinputstream from which the data is to be read. aoffset number of bytes that were sent in prev...
.... ainputstream an nsiinputstream from which the data is to be read. aoffset number of bytes that were sent in previous ondataavailable() calls for this request. in other words, the sum of all previous count parameters. if that number is greater than or equal to 2^32, this parameter will be pr_uint32_max (2^32 - 1). acount the number of bytes available for reading. you must read all of these bytes before returning to the caller. note: throwing an exception will cancel the request. ...
nsIThreadPool
id shutdown(); attributes attribute type description idlethreadlimit unsigned long get/set the maximum number of idle threads that are kept alive. once there are more than this many idle worker threads, the idle threads start getting destroyed. ...
...a listener that receives an nsithreadpoollistener.onthreadcreated() notification is guaranteed to always receive the corresponding nsithreadpoollistener.onthreadshuttingdown() notification. the thread pool takes ownership of the listener and releases it when the shutdown() method is called. ...
nsITimer
nsitimer instances must be initialized by calling one of the initialization methods. you may also re-initialize (using one of the initialization methods) an existing instance to avoid the overhead of destroying and creating a timer. it is not necessary to cancel the timer in that case. xpcom/threads/nsitimer.idlscriptable please add a summary to this article. ...
...ithfunccallback(). read only. native code only! delay unsigned long the timeout delay in millisecond. note: re-setting the delay on a one-shot timer that has already fired doesn't restart the timer. call one of the init() methods to restart a one-shot timer. target nsieventtarget the nsieventtarget to which the callback is dispatched. this target must be set before calling any of the initialization methods. type unsigned long defines the timer type: one shot, repeating slack or repeating precise. must be one of the constants defined under constants on this page. constants constant value description type_one_shot 0 type of a timer that fires once only. type_repeating_slack 1 after firi...
nsIWindowMediator
if any. nsidomwindow getouterwindowwithid( in unsigned long long aouterwindowid ); parameters aouterwindowid the id of the outer window, e.g., as obtained by nsidomwindowutils.outerwindowid. return value the dom window with the given id. if no window with the id exists, or the window exists but it is an inner window, null is returned instead. see also: inner and outer windows. note: before gecko 23.0, use nsidomwindowutils.getouterwindowwithid. windowmediator = components.classes["@mozilla.org/appshell/window-mediator;1"] .getservice(components.interfaces.nsiwindowmediator); if (!windowmediator.getouterwindowwithid) { windowmediator.getouterwindowwithid = function (aouterwindowid) { let win = this.getmostrecentwindow(); let winutil = win.queryinterface(component...
...nly windows of this type. ("type" is the |windowtype| attribute of the xml <window> element.) if null, all windows will be enumerated. afronttoback if true, the enumerator enumerates windows in order from front to back. back to front if false. return value an enumerator of nsidomwindows. this method may not work on linux or mac (bug 462222) nor on os2 (bug 370134) - please check those bugs before relying on it. more information can be found by searching mxr for broken_wm_z_order) getzorderxulwindowenumerator() identical to getzorderdomwindowenumerator() except returns an enumerator of nsixulwindow. nsisimpleenumerator getzorderxulwindowenumerator( in wstring awindowtype, in boolean afronttoback ); parameters awindowtype the returned enumerator will enumerate only windows of...
nsIWindowWatcher
iprompt getnewprompter( in nsidomwindow aparent ); parameters aparent the parent nsidomwindow used for posing alerts. can be null. return value a new nsiprompt object. getwindowbyname() retrieve an existing window (or frame). note: this method will search all open windows for any window or frame with the given window name. make sure you understand the security implications of this before using this method! nsidomwindow getwindowbyname( in wstring atargetname, in nsidomwindow acurrentwindow ); parameters atargetname the window name. acurrentwindow the nsidomwindow starting point in the window hierarchy to begin the search. if null, each top level window will be searched. return value the nsidomwindow with the target name. getwindowenumerator() get an nsisimplee...
...this was fixed in bug 509124. registernotification() 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 objec...
nsIXULBrowserWindow
and seamonkey also store their nsixulbrowserwindow reference in the global xulbrowserwindow object accessible from javascript code. note: the xulbrowserwindow object offered to javascript code provides a great many more methods and attributes than those listed here, which are only the ones available to c++ code. see the documentation for xulbrowserwindow for details. method overview astring onbeforelinktraversal(in astring originaltarget, in nsiuri linkuri, in nsidomnode linknode, in prbool isapptab); void setjsdefaultstatus(in astring status); void setjsstatus(in astring status); void setoverlink(in astring link, in nsidomelement element); methods onbeforelinktraversal() called before traversing a link to determine the appropriate target into which to load the link. this may be us...
...linkuri the uri of the link that is about to be traversed. linknode the nsidomnode representing the dom node in which the link is located. ...
Weak reference
why do i need this? when you hold an owning reference on an object (i.e., you have addrefed it), you are holding that object in existence for the duration of your reference. this isn't always appropriate, and can lead to trouble. ...
... ... else if ( aiid.equals(nscomtypeinfo<nsisupportsweakreference>::getiid()) ) *ainstancepr = ns_static_cast(nsisupportsweakreference*, this); // ... } alternatives this technique is useful, but in situations where you need this, there are two alternatives which you may want to consider: you might hold an owning reference, but arrange to release it out-of-band; this must be before the destructor, which would otherwise never be called. you might hold a raw pointer (without addrefing and releaseing it), and avoid using it in cases where it might dangle. see also the source xpcom/base/nsiweakreference.idl xpcom/glue/nsweakreference.h xpcom/glue/nsweakreference.cpp xpcom ownership guidelines using nscomptr original document information author: sc...
XPIDL
xample, the method '[binaryname(foo)] void bar();' becomes 'nsresult foo()' in native code (note that capitalization is still applied). however, the capitalization is not applied when using binaryname with attributes; i.e., [binaryname(foo)] readonly attribute quux bar; becomes getfoo(quux**) in native code. attributes named 'iid' and methods named 'getiid' are forbidden, although this is checked before binaryname conversion. the implicit_jscontext and optional_argc parameters are properties which help native code implementations determine how the call was made from script. if implicit_jscontext is present on a method, then an additional jscontext *cx parameter is added just after the regular list which receives the context of the caller. if optional_argc is present, then an additional uint8_t ...
...eceives the number of optional arguments that were actually used (obviously, you need to have an optional argument in the first place). note that if both properties are set, the jscontext *cx is added first, followed by the uint8_t _argc, and then ending with return value parameter. finally, as an exception to everything already mentioned, for attribute getters and setters the jscontext *cx comes before any other arguments. another native-only property is nostdcall. normally, declarations are made in the stdcall abi on windows to be abi-compatible with com interfaces. any non-scriptable method or attribute with nostdcall instead uses the thiscall abi convention. methods without this property generally use ns_imethod in their declarations and ns_imethodimp in their definitions to automatically a...
Thunderbird Binaries
a.org/pub/thunderbird/releases/ early preview releases whilst writing new versions of thunderbird, developers release preview versions, known as betas. these builds are made to get feedback from testers and extension developers. note: while beta builds have had some testing, they should be considered preview only and should not be used in a production environment. please read the release notes before downloading. preview releases are available from http://www.mozilla.org/thunderbird/channel/ nightly builds nightly builds are cutting-edge builds. they are built every 24 hours by the tinderboxes from the very latest source code. there are various sorts of nightly builds available for download. if you wish to download nightly builds to help us test for the next release, please read the testin...
...p://ftp.stage.mozaws.net/pub/thunderbird/nightly/latest-comm-central/ because the above two links currently do not work. frequently asked questions what is the trunk? the trunk is the central source code that is used for continuous and ongoing development. trunk builds contain the very latest bleeding-edge changes and updates. the trunk can be very unstable at times, so it's good to ask around before using trunk builds. what is a branch? branches are "forks" in the code, split from the trunk and destined to become end-user releases. at conception, a branch contains everything that the trunk contains, but from that point onwards, only certain fixes or changes will be accepted. therefore, over time, the branch becomes more stable. why branch? wouldn't it be better to have everyone working to...
Using the Multiple Accounts API
, is this server marked for offline download? preference: mail.server.server.override_namespaces - boolean, should we override namespaces on this server? ...
... the server preference: mail.server.server.empty_trash_threshhold integer, (should not be imap-specific) max k of wasted diskspace before we purge a folder preference: mail.server.server.delete_model - integer, delete model (move to trash, imap delete, purge immediately, not sure of values) preference: mail.server.server.timeout - integer, number of minutes a connection is idle before we drop it preference: mail.server.server.capability - list of capabilities of this server preference: mail.server.server.namespace.public - the server's namespace for public folders preference: mail.server.server.namespace.personal - the server's namespace for personal folders preference: mail.server.server.namespace.other_users - the server's namespace for other user's folders ...
Zombie compartments
o confirm that the relevant compartment is present. close the first page. minimize memory usage and remeasure in about:memory. it might be worth refreshing multiple times just to be sure. if the compartment is still present in about:memory, that's very suspicious. you could try waiting 20 minutes or so, then reload about:memory again. some zombie compartments stick around for a limited time before disappearing, others are immortal, and it's useful to know which is which. if you see any `ghost-windows` (at the bottom of about:memory) that is also suspicious, as they are similar to zombie compartments. some zombie compartments are caused by add-ons. if you have add-ons enabled, please try to reproduce in safe mode, which disables them. if you can identify, by disabling them one at a time...
...bie compartments. otherwise, please file a bug (using the "tech evangelism" product and the "add-ons" component), add "[memshrink]" to its whiteboard, and mark it as blocking bug 668871 and bug 700547. restartless add-ons should also take special care that all their compartments get destroyed after disabling or uninstalling the add-on. (please note that you may need to close the about:addons ui before changes are made). avoiding zombie compartments in add-ons once you know that an add-on causes a zombie compartment, the only way to identify the cause is to read the add-on's code. see common causes of memory leaks in extensions for things to avoid. ...
Mozilla
an update server the goal of this document is to provide instructions for installing a locally-served firefox update. signing mozilla apps for mac os x mac os x's gatekeeper functionality prevents users from launching applications that haven't been code-signed, in order to help keep their computers secure. firefox and thunderbird releases are both signed before shipping; this article describes the process. supported build targets page moved to the in-tree documentation: https://firefox-source-docs.mozilla.org/build/buildsystem/supported-configurations.html task graph after a change to the gecko source code is pushed to version-control, jobs for t...
...ns per-commit, only on mozilla-central. each task generates one or more json-formatted data files providing detailed information on tests run in continuous integration, typically broken down by bugzilla component. data files are typically consumed by dashboards, like www.arewefissionyet.com. testing mozilla code testing your code is important! before you can even get your code committed into the source tree, you have to test it, and larger patches have to have automated tests. these articles will help you master (and continue to excel at) testing mozilla code. the mozilla platform the mozilla project encompasses several technologies that, together, comprise the mozilla platform. these link...
Debugger.Frame - Firefox Developer Tools
s, find the lexical environment in which the execution is taking place, and so on. for a given debugger instance, spidermonkey creates only one debugger.frame instance for a given visible frame. every handler method called while the debuggee is running in a given frame is given the same frame object. similarly, walking 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. this allows the code using each debugger instance to place whatever properties it likes on it...
...ces the frame to return early (by returning a resumption value other than undefined), any remaining debuggers’ onstep handlers do not run. this property is ignored on frames that are not executing debuggee code, like "call" frames for calls to host functions and "debugger" frames. onpop this property must be either undefined or a function. if it is a function, spidermonkey calls it just before this frame is popped, passing a completion value indicating how this frame’s execution completed, and providing this debugger.frame instance as the this value. the function should return a resumption value indicating how execution should proceed. on newly created frames, this property’s value is undefined. when this handler is called, this frame’s current execution location, as reflected ...
All keyboard shortcuts - Firefox Developer Tools
inspector shift + f9 shift + f9 * shift + f9 open debugger 3 ctrl + shift + z cmd + opt + z ctrl + shift + z 1. unlike the other toolbox-hosted tools, this shortcut does not also close the web console. instead, it focuses on the web console's command line. to close the web console, use the global toolbox shortcut of ctrl + shift + i (cmd + opt + i on a mac). 2. before firefox 55, the keyboard shortcut was ctrl + shift + q (cmd + opt + q on a mac). 3. starting in firefox 71. before firefox 66, the letter in this shortcut was s. toolbox these shortcuts work whenever the toolbox is open, no matter which tool is active. command windows macos linux cycle through tools left to right ctrl + ] cmd + ] ctrl + ] cycle t...
... cmd + shift + b ctrl + shift + b 1. by default, on some macs, the function key is remapped to use a special feature: for example, to change the screen brightness or the volume. see this guide to using these keys as standard function keys. to use a remapped key as a standard function key, hold the function key down as well (so to open the profiler, use shift + function + f5). note: before firefox 66, the combination ctrl + shift + s on windows and linux or cmd + opt + s on macos would open/close the debugger. from firefox 66 and later, this is no longer the case. web console command windows macos linux open the web console ctrl + shift + k cmd + opt + k ctrl + shift + k search in the message display pane ctrl + f cmd + f c...
Examine and edit CSS - Firefox Developer Tools
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. ...
... ::after ::backdrop ::before ::first-letter ::first-line ::selection :-moz-color-swatch :-moz-number-spin-box :-moz-number-spin-down :-moz-number-spin-up :-moz-number-text :-moz-number-wrapper :-moz-placeholder :-moz-progress-bar :-moz-range-progress :-moz-range-thumb :-moz-range-track :-moz-selection if the selected element has pseudo-elements applied to it, they are displayed before the selected element but hidden by a disclosure triangle: clicking the triangle displays them: viewing common pseudo-classes there's a button to the right of the filter box: click the button to see checkboxes that you can use to enable the :hover, :active and :focus, :focus-within and :visited pseudo-classes for the selected element: this feature can also be accessed from the popup men...
Taking screenshots - Firefox Developer Tools
er's "downloads" directory: copying screenshots to the clipboard from firefox 53, you can also copy the screenshot to the clipboard. just check the box in settings labeled "screenshot to clipboard": now, whenever you take a screenshot, the screenshot is also copied to the clipboard. taking screenshots with the web console if you need to specify a different device-pixel-ratio, set a delay before 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 foll...
...then hit tab to autocomplete :screenshot. the command has the following optional parameters: command type description --clipboard boolean when present, this parameter will cause the screenshot to be copied to the clipboard. prevents saving to a file unless you use the --file option to force file writing. --delay number the number of seconds to delay before taking the screenshot; you can use an interger or floating point number. this is useful if you want to pop open a menu or invoke a hover state for the screenshot. --dpr number the device pixel ratio to use when taking the screenshot. values above 1 yield "zoomed-in" images, whereas values below 1 create "zoomed-out" images. --file boolean when present, the screenshot...
Tips - Firefox Developer Tools
he screenshot will be of the whole page, not just the section visible in the browser windows. the file name will have -fullpage appended to it as well. see web console helpers for all parameters. in the console output: click on the inspector icon () next to an element in the output to select it within the inspector. check "enable persistent logs" in the settings to keep logged messages from before even after navigation. check "enable timestamps" in the settings to show timestamps besides the logged messages. debugger skip javascript libraries in debugging sessions via the black box icon (). press ctrl+alt+f to search in all scripts. press ctrl+d to search for a function definition. press ctrl+l to go to a specific line. style editor the black box icon () in the style sheet pa...
...lick the options button in the style sheet pane and click "show original sources" to toggle the display of css preprocessor files. network monitor click the request summary to compare performance of cache vs. no-cache page loading. when a request is selected click "edit and resend" to modify its headers and send it again. check "enable persistent logs" in the settings to keep requests from before even after navigation. hover the "js" icon within the "cause" column to see the javascript stack trace, which caused the request. check "disable http cache (when toolbox is open)" in the settings to disable the network cache while debugging network issues. storage inspector right-click the column headers to open a menu allowing to toggle the display of the columns. right-click an entry an...
Using the Beacon API - Web APIs
this document contains examples of the beacon interfaces. see beacon api for an overview. navigator.sendbeacon() the 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. ...
...a beacon request to the server in the global browsing context. the method takes two arguments: the url and the data to send. the data argument is optional and its type may be an arraybufferview, blob, domstring, or formdata. if the browser successfully queues the request for delivery, the method returns true and returns false otherwise. the following example specifies a handler for the load and beforeunload events. the handler calls sendbeacon() with the current url. window.onload = window.onunload = function analytics(event) { if (!navigator.sendbeacon) return; var url = "https://example.com/analytics"; // create the data to send var data = "state=" + event.type + "&location=" + location.href; // send the beacon var status = navigator.sendbeacon(url, data); // log the data a...
Beacon API - Web APIs
the beacon interface is used to schedule an asynchronous and non-blocking request to a web server. beacon requests use the http post method and requests typically do not require a response. requests are guaranteed to be initiated before a page is unloaded and they are run to completion, without requiring a blocking request (for example xmlhttprequest). example use cases of the beacon api are logging activity and sending analytics data to the server. example code of the interfaces described in this document is included in using the beacon api. why use beacon? the beacon interface addresses the needs of analytics and diagnostics code that typically attempts to send data to a web server before unloading the document. sending the data any sooner may result in a missed opportunity to g...
... result in a missed opportunity to gather data. however, ensuring that the data is sent during the unloading of a document is something that has traditionally been difficult for developers. user agents will typically ignore asynchronous xmlhttprequests made in an unload handler. to solve this problem, analytics and diagnostics code will typically make a synchronous xmlhttprequest in an unload or beforeunload handler to submit the data. the synchronous xmlhttprequest forces the browser to delay unloading the document, and makes the next navigation appear to be slower. there is nothing the next page can do to avoid this perception of poor page load performance. there are other techniques used to ensure that data is submitted. one such technique is to delay the unload to submit data by creating a...
CanvasRenderingContext2D.putImageData() - Web APIs
e returned to an equivalent getimagedata() as different values. ...
... living standard ...
Drawing shapes with canvas - Web APIs
snext » now that we have set up our canvas environment, we can get into the details of how to draw on the canvas. by the end of this article, you will have learned how to draw rectangles, triangles, lines, arcs and curves, providing familiarity with some of the basic shapes. working with paths is essential when drawing objects onto the canvas and we will see how that can be done. the grid before we can start drawing, we need to talk about the canvas grid or coordinate space. our html skeleton from the previous page had a canvas element 150 pixels wide and 150 pixels high. to the right, you see this canvas with the default grid overlayed. normally 1 unit in the grid corresponds to 1 pixel on the canvas. the origin of this grid is positioned in the top left corner at coordinate (0,0). all ...
...0); ctx.fill(); } } screenshotlive sample rectangles in addition to the three methods we saw in drawing rectangles, which draw rectangular shapes directly to the canvas, there's also the rect() method, which adds a rectangular path to a currently open path. rect(x, y, width, height) draws a rectangle whose top-left corner is specified by (x, y) with the specified width and height. before this method is executed, the moveto() method is automatically called with the parameters (x,y). in other words, the current pen position is automatically reset to the default coordinates. making combinations so far, each example on this page has used only one type of path function per shape. however, there's no limitation to the number or types of paths you can use to create a shape. so in this...
ChildNode.replaceWith() - Web APIs
u can polyfill the replacewith() method in internet explorer 10+ and higher with the following code: function replacewithpolyfill() { 'use-strict'; // for safari, and ie > 10 var parent = this.parentnode, i = arguments.length, currentnode; if (!parent) return; if (!i) // if there are no arguments parent.removechild(this); while (i--) { // i-- decrements i and returns the value of i before the decrement currentnode = arguments[i]; if (typeof currentnode !== 'object'){ currentnode = this.ownerdocument.createtextnode(currentnode); } else if (currentnode.parentnode){ currentnode.parentnode.removechild(currentnode); } // the value of "i" below is after the decrement if (!i) // if currentnode is the first argument (currentnode === arguments[0]) ...
...node = this.ownerdocument.createtextnode(currentnode); } else if (currentnode.parentnode){ currentnode.parentnode.removechild(currentnode); } // the value of "i" below is after the decrement if (!i) // if currentnode is the first argument (currentnode === arguments[0]) parent.replacechild(currentnode, this); else // if currentnode isn't the first parent.insertbefore(currentnode, this.nextsibling); } } if (!element.prototype.replacewith) element.prototype.replacewith = replacewithpolyfill; if (!characterdata.prototype.replacewith) characterdata.prototype.replacewith = replacewithpolyfill; if (!documenttype.prototype.replacewith) documenttype.prototype.replacewith = replacewithpolyfill; specification specification status comment ...
ChildNode - Web APIs
Web › API › ChildNode
the childnode mixin contains methods and properties that are common to all types of node objects that can have a parent. it's implemented by element, documenttype, and characterdata objects. properties there are neither inherited, nor specific properties. methods there are no inherited methods. childnode.remove() removes this childnode from the children list of its parent. childnode.before() inserts a set of node or domstring objects in the children list of this childnode's parent, just before this childnode. domstring objects are inserted as equivalent text nodes. childnode.after() inserts a set of node or domstring objects in the children list of this childnode's parent, just after this childnode. domstring objects are inserted as equivalent text nodes. childnode.replacewit...
...lent text nodes. specifications specification status comment domthe definition of 'childnode' in that specification. living standard split the elementtraversal interface in parentnode and childnode. previouselementsibling and nextelementsibling are now defined on the latter. the characterdata and documenttype implemented the new interfaces. added the remove(), before(), after() and replacewith() methods. element traversal specificationthe definition of 'elementtraversal' in that specification. obsolete added the initial definition of its properties to the elementtraversal pure interface and use it on element. polyfill external on github: childnode.js ...
CustomEvent - Web APIs
structor customevent() creates a customevent. properties customevent.detail read only any data passed when initializing the event. this interface inherits properties from its parent, event: event.bubbles read only a boolean indicating whether or not the event bubbles up through the dom. event.cancelbubble a historical alias to event.stoppropagation(). setting its value to true before returning from an event handler prevents propagation of the event. event.cancelable read only a boolean indicating whether the event is cancelable. event.composed read only a boolean indicating whether or not the event can bubble across the boundary between the shadow dom and the regular dom. event.currenttarget read only a reference to the currently registered target for the event. this...
...vent has bubbled. event.defaultprevented read only indicates whether or not the call to event.preventdefault() canceled the event. event.eventphase read only indicates which phase of the event flow is being processed. event.explicitoriginaltarget read only the explicit original target of the event (mozilla-specific.) event.originaltarget read only the original target of the event, before any retargetings. (mozilla-specific.) event.returnvalue a historical property introduced by internet explorer and eventually adopted into the dom specification in order to ensure existing sites continue to work. ideally, you should try to use event.preventdefault() and event.defaultprevented instead, but you can use returnvalue if you choose to do so. event.srcelement a non-standard alias (...
DisplayMediaStreamConstraints - Web APIs
the displaymediastreamconstraints dictionary is used to specify whether or not to include video and/or audio tracks in the mediastream to be returned by getdisplaymedia(), as well as what type of processing must be applied to the tracks. processing information is specified using mediatrackconstraints objects providing options which are applied to the track after the media data is received but before it is made available on the mediastream. properties audio a boolean or mediatrackconstraints value; if a boolean, this value simply indicates whether or not to include an audio track in the mediastream returned by getdisplaymedia(). if a mediatrackconstraints object is provided here, an audio track is included in the stream, but the audio is processed to match the specified constraints after be...
...m. properties audio a boolean or mediatrackconstraints value; if a boolean, this value simply indicates whether or not to include an audio track in the mediastream returned by getdisplaymedia(). if a mediatrackconstraints object is provided here, an audio track is included in the stream, but the audio is processed to match the specified constraints after being retrieved from the hardware but before being added to the mediastream. the default value is false. video if true (the default), the display contents are included in a mediastreamtrack within the stream provided by getdisplaymedia(). optionally, a mediatrackconstraints object may be given, providing options specifying processing to be performed on the video data before adding it to the stream. a value of false is not permitted, and r...
Document.createProcessingInstruction() - Web APIs
syntax pinode = document.createprocessinginstruction(target, data) parameters pinode is the resulting processinginstruction node. target is a string containing the first part of the processing instruction (i.e., <?target … ?>) data is a string containing any information the processing instruction should carry, after the target. ...
...ame that doesn't contain "xml", "xml", or any case combination of the two, other than standardized ones such as <?xml-stylesheet ?>. the closing processing instruction sequence (?>) is part of the data. example var doc = new domparser().parsefromstring('<foo />', 'application/xml'); var pi = doc.createprocessinginstruction('xml-stylesheet', 'href="mycss.css" type="text/css"'); doc.insertbefore(pi, doc.firstchild); console.log(new xmlserializer().serializetostring(doc)); // displays: <?xml-stylesheet href="mycss.css" type="text/css"?><foo/> specifications specification status comment domthe definition of 'createprocessinginstruction()' in that specification. living standard no change dom4the definition of 'createprocessinginstruction()' in ...
Document.importNode() - Web APIs
unlike document.adoptnode(), the original node is not removed from its original document. the imported node is a clone of the original. ...
...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.importnode(oldnode, true); document.getelementbyid("container").appendchild(newnode); notes before they can be inserted into the current document, nodes from external documents should either be: cloned using document.importnode(); or adopted using document.adoptnode(). best practice: although firefox doesn't currently enforce this rule, we encourage you to follow this rule for improved future compatibility. for more on the node.ownerdocument issues, see the w3c dom faq. specification...
Element.classList - Web APIs
Web › API › Element › classList
see https://bugzilla.mozilla.org/show_bug.cgi?id=814014 polyfill the legacy onpropertychange event can be used to create a living classlist mockup thanks to a element.prototype.classname property that fires the specified event once it is changed. the following polyfill for both classlist and domtokenlist ensure...
... return {next: function() { return nextindex<that.length ? {value: nextindex++, done: false} : {done: true}; }}; }; })(window.domtokenlist.prototype, window.document.createelement("div").classlist); })(window); caveats the polyfill is limited in functionality. it's currently unable to polyfill out-of-document-elements (e.g. elements created by document.createelement before they are appended to a parent node) in ie6-7. however, it should work just fine in ie9. a major discrepancy between the polyfilled version of classlist and the w3 specs is that for ie6-8, there is no way to create an immutable object (an object whose properties cannot be directly modified). in ie9, however, it is possible through extending the prototype, freezing the visible object, and overwrit...
EventTarget.dispatchEvent() - Web APIs
t is used to initialize the event.target and determine which event listeners to invoke. return value the return value is false if event is cancelable and at least one of the event handlers which received event called event.preventdefault(). otherwise it returns true. the dispatchevent() method throws unspecified_event_type_err if the event's type was not specified by initializing the event before the method was called, or if the event's type is null or an empty string. exceptions exceptions thrown by event handlers are reported as uncaught exceptions. the event handlers run on a nested callstack; they block the caller until they complete, but exceptions do not propagate to the caller. notes unlike "native" events, which are fired by the dom and invoke event handlers asynchronously via...
...re reported as uncaught exceptions. the event handlers run on a nested callstack; they block the caller until they complete, but exceptions do not propagate to the caller. notes unlike "native" events, which are fired by the dom and invoke event handlers asynchronously via the event loop, dispatchevent() invokes event handlers synchronously. all applicable event handlers will execute and return before the code continues on after the call to dispatchevent(). dispatchevent() is the last step of the create-init-dispatch process, which is used for dispatching events into the implementation's event model. the event can be created using event constructor. see also the event object reference. example see creating and triggering events. specifications specification status comment ...
Using Fetch - Web APIs
epts exactly the same parameters as the fetch() method. you can even pass in an existing request object to create a copy of it: const anotherrequest = new request(myrequest, myinit); this is pretty useful, as request and response bodies are one use only. making a copy like this allows you to make use of the request/response again while varying the init options if desired. the copy must be made before the body is read, and reading the body in the copy will also mark it as read in the original request. note: there is also a clone() method that creates a copy. both methods of creating a copy will fail if the body of the original request or response has already been read, but reading the body of a cloned response or request will not cause it to be marked as read in the original. headers the ...
...alid http header name. the mutation operations will throw a typeerror if there is an immutable guard (see below). otherwise, they fail silently. for example: const myresponse = response.error(); try { myresponse.headers.set('origin', 'http://mybank.com'); } catch (e) { console.log('cannot pretend to be a bank!'); } a good use case for headers is checking whether the content type is correct before you process it further. for example: fetch(myrequest) .then(response => { const contenttype = response.headers.get('content-type'); if (!contenttype || !contenttype.includes('application/json')) { throw new typeerror("oops, we haven't got json!"); } return response.json(); }) .then(data => { /* process your data further */ }) .catch(error => console.err...
Using files from web applications - Web APIs
ieve the datatransfer field from the event, pull the file list out of it, and then pass that to handlefiles(). from this point on, handling the files is the same whether the user used the input element or drag and drop. example: showing thumbnails of user-selected images let's say you're developing the next great photo-sharing website and want to use html to display thumbnail previews of images before the user actually uploads them. you can establish your input element or drop zone as discussed previously and have them call a function such as the handlefiles() function below. function handlefiles(files) { for (let i = 0; i < files.length; i++) { const file = files[i]; if (!file.type.startswith('image/')){ continue } const img = document.createelement("img"); img.classlist.
.../paul/demos/resources/webservices/devnull.php"); xhr.overridemimetype('text/plain; charset=x-user-defined-binary'); reader.onload = function(evt) { xhr.send(evt.target.result); }; reader.readasbinarystring(file); } the fileupload() function shown above creates a throbber, which is used to display progress information, and then creates an xmlhttprequest to handle uploading the data. before actually transferring the data, several preparatory steps are taken: the xmlhttprequest's upload progress listener is set to update the throbber with new percentage information so that as the upload progresses the throbber will be updated based on the latest information. the xmlhttprequest's upload load event handler is set to update the throbber progress information to 100% to ensure the pro...
Force Touch events - Web APIs
. there may also be large incompatibilities between implementations and the behavior may change in the future. force touch events are a proprietary, apple-specific feature which makes possible (where supported by the input hardware) new interactions based on how hard the user clicks or presses down on the touchscreen or trackpad. events webkitmouseforcewillbegin this event is fired before the mousedown event. its main use is that it can be event.preventdefault()ed. webkitmouseforcedown this event is fired after the mousedown event as soon as sufficient pressure has been applied for it to qualify as a "force click". webkitmouseforceup this event is fired after the webkitmouseforcedown event as soon as the pressure has been reduced sufficiently to end the "force click". web...
... soon as sufficient pressure has been applied for it to qualify as a "force click". webkitmouseforceup this event is fired after the webkitmouseforcedown event as soon as the pressure has been reduced sufficiently to end the "force click". webkitmouseforcechanged this event is fired each time the amount of pressure changes. this event first fires after the mousedown event and stops firing before the mouseup event. event properties the following property is known to be available on the webkitmouseforcewillbegin, mousedown, webkitmouseforcechanged, webkitmouseforcedown, webkitmouseforceup, mousemove, and mouseup event objects: mouseevent.webkitforce read only the amount of pressure currently being applied to the trackpad/touchscreen constants these constants are useful for det...
Fullscreen API - Web APIs
64 full support 64 no support 47 — 65disabled disabled from version 47 until version 65 (exclusive): this feature is behind the full-screen-api.unprefix.enabled preference (needs to be set to true). to change preferences in firefox, visit about:config. no support 9 — 65notes alternate name notes before firefox 44, firefox incorrectly allowed elements inside a <frame> or <object> element to request, and to be granted, fullscreen. in firefox 44 and onwards this has been fixed: only elements in the top-level document or in an <iframe> element with the allowfullscreen attribute can be displayed fullscreen.alternate name uses the non-standard name: mozrequestfullscreenie full support...
... 64 full support 64 no support 47 — 65disabled disabled from version 47 until version 65 (exclusive): this feature is behind the full-screen-api.unprefix.enabled preference (needs to be set to true). to change preferences in firefox, visit about:config. no support 9 — 65notes alternate name notes before firefox 44, firefox incorrectly allowed elements inside a <frame> or an <object> to request, and to be granted, fullscreen. in firefox 44 and onwards this has been fixed: only elements in the top-level document or in an <iframe> with the allowfullscreen attribute can be displayed fullscreen.alternate name uses the non-standard name: mozrequestfullscreenopera android full support ...
GlobalEventHandlers.ontransitioncancel - Web APIs
the ontransitioncancel property of the globaleventhandlers mixin is an eventhandler that processes transitioncancel events. the transitioncancel event is sent when a css transition is cancelled. the transition is cancelled when: the value of the transition-property property that applies to the target is changed the display property is set to "none". the transition is stopped before it has run to completion, e.g. by moving the mouse off a hover-transitioning element. syntax var transitioncancelhandler = target.ontransitioncancel; target.ontransitioncancel = function value a function to be called when a transitioncancel event occurs indicating that a css transition has been cancelled on the target, where the target object is an html element (htmlelement), document (document), or wind...
... specification specification status comment css transitionsthe definition of 'ontransitioncancel' in that specification. working draft ...
HTMLAnchorElement - Web APIs
ntaining a valid url of a linked resource. htmlanchorelement.hreflang is a domstring that reflects the hreflang html attribute, indicating the language of the linked resource. htmlanchorelement.media is a domstring that reflects the media html attribute, indicating the intended media for the linked resource. htmlhyperlinkelementutils.password is a usvstring containing the password specified before the domain name. htmlhyperlinkelementutils.origin read only returns a usvstring containing the origin of the url, that is its scheme, its domain and its port. htmlhyperlinkelementutils.pathname is a usvstring representing the path name component, if any, of the referenced url. htmlhyperlinkelementutils.port is a usvstring representing the port component, if any, of the referenced url. htm...
...ring that reflects the target html attribute, indicating where to display the linked resource. htmlanchorelement.text is a domstring being a synonym for the node.textcontent property. htmlanchorelement.type is a domstring that reflects the type html attribute, indicating the mime type of the linked resource. htmlhyperlinkelementutils.username is a usvstring containing the username specified before the domain name. obsolete properties htmlanchorelement.charset is a domstring representing the character encoding of the linked resource. htmlanchorelement.coords is a domstring representing a comma-separated list of coordinates. htmlanchorelement.name is a domstring representing the anchor name. htmlanchorelement.rev is a domstring representing that the rev html attribute, sp...
HTMLAreaElement - Web APIs
flang html attribute, indicating the language of the linked resource. htmlareaelement.media is a domstring containing that reflects the media html attribute, indicating target media of the linked resource. htmlareaelement.nohref is a boolean flag indicating if the area is inactive (true) or active (false). htmlhyperlinkelementutils.password is a usvstring containing the password specified before the domain name. htmlhyperlinkelementutils.origin read only returns a usvstring containing the origin of the url, that is its scheme, its domain and its port. htmlhyperlinkelementutils.pathname is a usvstring containing the path name component, if any, of the referenced url. htmlhyperlinkelementutils.port is a usvstring containing the port component, if any, of the referenced url. htmlhyp...
...ent's position in the tabbing order. htmlareaelement.target is a domstring that reflects the target html attribute, indicating the browsing context in which to open the linked resource. htmlareaelement.type is a domstring that reflects the type html attribute, indicating the mime type of the linked resource. htmlhyperlinkelementutils.username is a usvstring containing the username specified before the domain name. methods inherits methods from its parent, htmlelement, and implements 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 ...
HTMLElement: transitioncancel event - Web APIs
transition-property: transform background; transition-duration: 2s; transition-delay: 2s; } .transition:hover { transform: rotate(90deg); background: rgba(255,0,0,0); } to this, we'll add some javascript to indicate that the transitionstart, transitionrun, transitioncancel and transitionend events fire. in this example, to cancel the transition, stop hovering over the transitioning box before the transition ends. for the transition end event to fire, stay hovered over the transition until the transition ends. const message = document.queryselector('.message'); const el = document.queryselector('.transition'); el.addeventlistener('transitionrun', function() { message.textcontent = 'transitionrun fired'; }); el.addeventlistener('transitionstart', function() { message.textcontent ...
... if there is no transition delay or duration, if both are 0s or neither is declared, there is no transition, and none of the transition events are fired. if the transitioncancel event is fired, the transitionend event will not fire. specifications specification status comment css transitionsthe definition of 'transitioncancel' in that spe...
HTMLElement: transitionend event - Web APIs
bubbles yes cancelable yes interface transitionevent event handler property ontransitionend the transitionend event is fired in both directions - as it finishes transitioning to the transitioned state, and when it fully reverts to the default or non-transitioned state. ...
... transition-property: transform background; transition-duration: 2s; transition-delay: 1s; } .transition:hover { transform: rotate(90deg); background: rgba(255,0,0,0); } to this, we'll add some javascript to indicate that the transitionstart, transitionrun, transitioncancel and transitionend events fire. in this example, to cancel the transition, stop hovering over the transitioning box before the transition ends. for the transition end event to fire, stay hovered over the transition until the transition ends. const message = document.queryselector('.message'); const el = document.queryselector('.transition'); el.addeventlistener('transitionrun', function() { message.textcontent = 'transitionrun fired'; }); el.addeventlistener('transitionstart', function() { message.textcontent ...
HTMLElement: transitionrun event - Web APIs
the transitionrun event is fired when a css transition is first created, i.e. before any transition-delay has begun. bubbles yes cancelable no interface transitionevent event handler property ontransitionrun examples this code adds a listener to the transitionrun event: el.addeventlistener('transitionrun', () => { console.log('transition is running but hasn\'t necessarily started transitioning yet'); }); the same, but using the ontransitionrun property instead of addeventlistener(): el.ontransitionrun = () => { console.log('transition started running, and will start transitioning when the transition delay has expired'); }; live example in the following example, we have a simple <div> element, styled with a transition t...
...sitionstart fired'; }); el.addeventlistener('transitionend', function() { message.textcontent = 'transitionend fired'; }); the difference is that: transitionrun fires when the transition is created (i.e. at the start of any delay). transitionstart fires when the actual animation has begun (i.e. at the end of any delay). the transitionrun will occur even if the transition is canceled before the delay expires. if there is no transition delay or if transition-delay is negative, both transitionrun and transitionstart are fired. specifications specification status comment css transitionsthe definition of 'transitionrun' in that specification. working draft ...
HTMLScriptElement - Web APIs
ent.referrerpolicy is a domstring that reflects the referrerpolicy html attribute indicating which referrer to use when fetching the script, and fetches done by that script. methods no specific methods; inherits methods from its parent, htmlelement. examples dynamically importing scripts let's create a function that imports new scripts within a document creating a <script> node immediately before the <script> that hosts the following code (through document.currentscript). these scripts will be asynchronously executed. for more details, see the defer and async properties. function loaderror(oerror) { throw new urierror("the script " + oerror.target.src + " didn't load correctly."); } function prefixscript(url, onloadfunction) { var newscript = document.createelement("script"); news...
...ore 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 (onloadfunction) { newscript.onload = onloadfunction; } document.currentscript.parentnode.insertbefore(newscript, document.currentscript); newscript.src = url; } this next function, instead of prepending the new scripts immediately before the document.currentscript element, appends them as children of the <head> tag. function loaderror(oerror) { throw new urierror("the script " + oerror.target.src + " didn't load correctly."); } function affixscripttohead(url, onloadfunction) { var newscr...
History.state - Web APIs
Web › API › History › state
story.state property returns a value representing the state at the top of the history stack. this is a way to look at the state without having to wait for a popstate event. syntax const currentstate = history.state value the state at the top of the history stack. the value is null until the pushstate() or replacestate() method is used. ...
...y stack. the value is null until the pushstate() or replacestate() method is used. examples the code below logs the value of history.state before using the pushstate() method to push a value to the history. the next line logs the value to the console again, showing that history.state now has a value. // should be null because we haven't modified the history stack yet console.log(`history.state before pushstate: ${history.state}`); // now push something on the stack history.pushstate({name: 'example'}, "pushstate example", 'page3.html'); // now state has a value. console.log(`history.state after pushstate: ${history.state}`); specificationse specification status comment html living standardthe definition of 'history.state' in that specification. living standard ...
IDBDatabase.transaction() - Web APIs
ransactions 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 firefox 40+ the complete event is fired after the os has been told to write the data but potentially before that data has actually been flushed to disk. the complete event may thus be delivered quicker than before, however, there exists a small chance that the entire transaction will be lost if the os crashes or there is a loss of system power before the data is flushed to disk. since such catastrophic events are rare most consumers should not need to concern themselves further. note: in firefox, i...
...transaction will be lost if the os crashes or there is a loss of system power before the data is flushed to disk. since such catastrophic events are rare most consumers should not need to concern themselves further. note: in firefox, if you wish to ensure durability for some reason (e.g. you're storing critical data that cannot be recomputed later) you can force a transaction to flush to disk before delivering the complete event by creating a transaction using the experimental (non-standard) readwriteflush mode (see idbdatabase.transaction.) this is currently experimental, and can only be used if the dom.indexeddb.experimental pref is set to true in about:config. details optional dictionary of other settings, supported only by chrome: return value an idbtransaction object. exceptio...
IDBTransaction.oncomplete - Web APIs
ransactions 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 firefox 40+ the complete event is fired after the os has been told to write the data but potentially before that data has actually been flushed to disk. the complete event may thus be delivered quicker than before, however, there exists a small chance that the entire transaction will be lost if the os crashes or there is a loss of system power before the data is flushed to disk. note: this feature is available in web workers. note: in firefox, if you wish to ensure durability for some reason (e.g. y...
..., however, there exists a small chance that the entire transaction will be lost if the os crashes or there is a loss of system power before the data is flushed to disk. note: this feature is available in web workers. note: in firefox, if you wish to ensure durability for some reason (e.g. you're storing critical data that cannot be recomputed later) you can force a transaction to flush to disk before delivering the complete event by creating a transaction using the experimental (non-standard) readwriteflush mode (see idbdatabase.transaction.) this is currently experimental, and can only be used if the dom.indexeddb.experimental pref is set to true in about:config. syntax transaction.oncomplete = function(event) { ... }; example in the following code snippet, we open a read/write transact...
IDBTransaction - Web APIs
refox durability guarantees note that as of firefox 40, indexeddb transactions have relaxed durability guarantees to increase performance (see bug 1112702.) previously in a readwrite transaction idbtransaction.oncomplete was fired only when all data was guaranteed to have been flushed to disk. in firefox 40+ the complete event is fired after the os has been told to write the data but potentially before that data has actually been flushed to disk. the complete event may thus be delivered quicker than before, however, there exists a small chance that the entire transaction will be lost if the os crashes or there is a loss of system power before the data is flushed to disk. since such catastrophic events are rare, most consumers should not need to concern themselves further. if you must ensure du...
... properties idbtransaction.db read only the database connection with which this transaction is associated. ...
Checking when a deadline is due - Web APIs
var monthnumber = 1; break; // other lines removed from listing for brevity case "december": var monthnumber = 11; break; default: alert('incorrect month entered in database.'); } the first thing we do is convert the month names we have stored in the database into a month number that javascript will understand. as we saw before, the javascript date object creates month values as a number between 0 and 11. if(+(cursor.value.hours) == hourcheck && +(cursor.value.minutes) == minutecheck && +(cursor.value.day) == daycheck && monthnumber == monthcheck && cursor.value.year == yearcheck && notified == "no") { // if the numbers all do match, run the createnotifica...
...check && notified == "no") { // if the numbers all do match, run the createnotification() // function to create a system notification createnotification(cursor.value.tasktitle); } with the current time and date segments that we want to check against the indexeddb stored values all assembled, it is time to perform the checks. we want all the values to match before we show the user some kind of notification to tell them their deadline is up. the + operator in this case converts numbers with leading zeros into their non 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...
IntersectionObserver.rootMargin - Web APIs
the intersectionobserver interface's read-only rootmargin property is a string with syntax similar to that of the css margin property. each side of the rectangle represented by rootmargin is added to the corresponding side in the root element's bounding box before the intersection test is performed. this lets you, for example, adjust the bounds outward so that the target element is considered 100% visible even if a certain number of pixels worth of width or height is clipped away, or treat the target as partially hidden if an edge is too close to the edge of the root's bounding box. see the root element and root margin in intersection observer api for a more in-depth look at the root margin and how it works with the root's bounding box. syntax var marginstring = intersectionobserve...
...section observer api for a more in-depth look at the root margin and how it works with the root's bounding box. syntax var marginstring = intersectionobserver.rootmargin; value a string, formatted similarly to the css margin property's value, which contains offsets for one or more sides of the root's bounding box. these offsets are added to the corresponding values in the root's bounding box before the intersection between the resulting rectangle and the target element's bounds. the string returned by this property may not match the one specified when the intersectionobserver was instantiated. the browser is permitted to alter the values if rootmargin isn't specified when the object was instantiated, it defaults to the string "0px 0px 0px 0px", meaning that the intersection will be comput...
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 keyboard. ...
... there are several ways this code can be made better. most real games would watch for keydown events, start motion when that happens, and stop the motion when the corresponding keyup occurs, instead of relying on key repeats. that would allow both smoother and faster movement, but would also allow the player to be moving and steering at the same time. transitions or animations co...
KeyboardEvent - Web APIs
ean the user expects a "z" and all the other properties would indicate a "z") or a dvorak keyboard layout (where the user would expect an "f"). keyboardevent.ctrlkey read only returns a boolean that is true if the ctrl key was active when the key event was generated. keyboardevent.iscomposing read only returns a boolean that is true if the event is fired between after compositionstart and before compositionend. keyboardevent.key read only returns a domstring representing the key value of the key represented by the event. keyboardevent.locale read only returns a domstring representing a locale string indicating the locale the keyboard is configured for. this may be the empty string if the browser or device doesn't know the keyboard's locale. note: this does not describe the locale ...
...orms, then, an auto-repeat key will generate the following sequence of events: keydown keypress keyup keydown keypress keyup <<repeating until the user releases the key>> keyup in these environments, unfortunately, there's no way for web content to tell the difference between auto-repeating keys and keys that are just being pressed repeatedly. auto-repeat handling prior to gecko 5.0 before gecko 5.0 (firefox 5.0 / thunderbird 5.0 / seamonkey 2.2), keyboard handling was less consistent across platforms. windows auto-repeat behavior is the same as in gecko 4.0 and later. mac after the initial keydown event, only keypress events are sent until the keyup event occurs; the inter-spaced keydown events are not sent. linux the event behavior depends on the specific platform. it wil...
LargestContentfulPaint - Web APIs
the timing of this paint is a good heuristic for when the main page content is available during load. properties largestcontentfulpaint.element the element that is the current largest contentful paint. largestcontentfulpaint.rendertime the time the element was rendered to the screen. may not be available if the element is a cross-origin image loaded without the timing-allow-origin header. largestcontentfulpaint.loadtime the time the element was loaded. ...
...int.url if the element is an image, the request url of the image. methods largestcontentfulpaint.tojson() returns the above properties as json. examples the following example shows how to create a performanceobserver that listens for largest-contentful-paint entries and logs the lcp value to the console. this example also demonstrates how to include buffered entries (those that ocurred before observer() was called), which is done by setting the buffered option to true. note that in this example data is only sent to the server when the user leaves the tab. // catch errors since some browsers throw when using the new `type` option. // https://bugs.webkit.org/show_bug.cgi?id=209216 try { let lcp; const po = new performanceobserver((entrylist) => { const entries = entrylist.get...
Recording a media element - Web APIs
t(lengthinms).then( () => recorder.state == "recording" && recorder.stop() ); return promise.all([ stopped, recorded ]) .then(() => data); } startrecording() takes two input parameters: a mediastream to record from and the length in milliseconds of the recording to make. we always record no more than the specified number of milliseconds of media, although if the media stops before that time is reached, mediarecorder automatically stops recording as well. line 2 creates the mediarecorder that will handle recording the input stream. line 3 creates an empty array, data, which will be used to hold the blobs of media data provided to our ondataavailable event handler. line 5 sets up the handler for the dataavailable event. the received event's data property is a blob th...
... promise which resolves when the preview video starts to play is created and returned. line 10 when the preview video begins to play, we know there's media to record, so we respond by calling the startrecording() function we created earlier, passing in the preview video stream (as the source media to be recorded) and recordingtimems as the number of milliseconds of media to record. as mentioned before, startrecording() returns a promise whose resolution handler is called (receiving as input an array of blob objects containing the chunks of recorded media data) once recording has completed. lines 11-15 the recording process's resolution handler receives as input an array of media data blobs locally known as recordedchunks. the first thing we do is merge the chunks into a single blob whose mim...
Using the MediaStream Recording API - Web APIs
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 this before? why was css2 layout so awkward?" it allows you do a calculation to determine the computed value of a css unit, mixing different units in the process. for example, in web dictaphone we have three main ui areas, stacked vertically. we wanted to give the first two (the header and the controls) fixed heights: header { height: 70px; } .main-controls { padding-bottom: 0.7rem; height: 170px; }...
...next, we call getusermedia() and inside it define: the constraints: only audio is to be captured for our dictaphone. the success callback: this code is run once the getusermedia call has been completed successfully. the error/failure callback: the code is run if the getusermedia call fails for whatever reason. note: all of the code below is placed inside the getuser...
MediaStream Recording API - Web APIs
ataavailable event to occur, thereby delivering the latest sound to you so you can filter it, save it, or whatever. recording stops automatically when the source media stops playing. you can stop recording at any time by calling mediarecorder.stop(). note: individual blobs containing slices of the recorded media will not necessarily be individually playable. the media needs to be reassembled before playback. if anything goes wrong during recording, an error event is sent to the mediarecorder. you can listen for error events by setting up a onerror event handler. example here, we use an html canvas as source of the mediastream, and stop recording after 9 seconds. var canvas = document.queryselector("canvas"); // optional frames per second argument. var stream = canvas.capturestream(25...
...the recording process, and its pause() and resume() methods to pause and resume recording of the source media. if you need or want to check to see if a specific mime type is supported, that's possible as well. just call mediarecorder.istypesupported(). examining potential input sources if your goal is to record camera and/or microphone input, you may wish to examine the available input devices before beginning the process of constructing the mediarecorder. to do so, you'll need to call navigator.mediadevices.enumeratedevices() to get a list of the available media devices. you can then examine that list and identify the potential input sources, and even filter the list based on desired criteria. in this code snippet, enumeratedevices() is used to examine the available input devices, locate th...
Transcoding assets for Media Source Extensions - Web APIs
this article takes you through the requirements and shows you a toolchain you can use to encode your assets appropriately. getting started the first and most important step is to ensure that your files are comprised of a container and codec that users' browsers support. depending on the codec, you might need to fragment the file to comply with the iso bmff spec. (optional) if you decide to use dynamic adaptive streaming over http (dash) for adaptive bitrate streaming, you need to transcode your assets into multiple resolutions. ...
...set metadata and creating content for dash. to install, you'll need to build/compile the application yourself from the provided project files/source files, depending on your os and preferences. see the building instructions for more details. the prebuilt file is here. put the contents of the bin directory in the same place as ffmpeg. python2 — bento4 uses it. get these installed successfully before moving to the next step. sample media should be placed in the bento4 utils directory and worked here. note: the prebuilt ffmpeg does not include libfdk_aac due to licensing reasons. bento4 uses this by default, so you need to compile ffmpeg if necessary. if you don't need it, add --audio-codec=aac to the mp4-dash-encode.py command line. container and codec support as specified in section 1.
Navigator.sendBeacon() - Web APIs
l receive the data. can be relative or absolute. data a arraybuffer, arraybufferview, blob, domstring, formdata, or urlsearchparams object containing the data to send. return values the sendbeacon() method returns true if the user agent successfully queued the data for transfer. otherwise, it returns false. description this method is for analytics and diagnostics that send data to a server before the document is unloaded, where sending 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, ...
...ata has been sent during the unloading of a document has traditionally been difficult, because user agents typically ignore asynchronous xmlhttprequests made in an unload handler. historically, this was addressed with some of the following workarounds to delay the page unload long enough to send data to some url: submitting the data with a blocking synchronous xmlhttprequest call in unload or beforeunload event handlers. creating an <img> element and setting its src in the unload handler. most user agents will delay the unload to load the image. creating a no-op loop for several seconds in the unload handler. all of these methods block unloading the document, which slows down the next navigation. there is nothing the next page can do to avoid this, so the new page seems slow, even though...
Node - Web APIs
Web › API › Node
olean value indicating whether or not a node is a descendant of the calling node. node.getboxquads() returns a list of the node's css boxes relative to another node. node.getrootnode() returns the context object's root which optionally includes the shadow root if it is available. node.haschildnodes() returns a boolean indicating whether or not the element has any child nodes. node.insertbefore() inserts a node before the reference node as a child of a specified parent node. node.isdefaultnamespace() accepts a namespace uri as an argument and returns a boolean with a value of true if the namespace is the default namespace on the given node or false if not. node.isequalnode() returns a boolean which indicates whether or not two nodes are of the same type and all their defining data ...
...efinition of 'node' in that specification. obsolete removed the following properties: attributes, namespaceuri, prefix, and localname. removed the following methods: issupported(), hasattributes(), getfeature(), setuserdata(), and getuserdata(). document object model (dom) level 3 core specificationthe definition of 'node' in that specification. obsolete the methods insertbefore(), replacechild(), removechild(), and appendchild() returns one more kind of error (not_supported_err) if called on a document. the normalize() method has been modified so that text node can also be normalized if the proper domconfiguration flag is set. added the following methods: comparedocumentposition(), issamenode(), lookupprefix(), isdefaultnamespace(), lookupnamespaceuri(), isequal...
NodeIterator - Web APIs
ows text nodes. nodeiterator.filter read only returns a nodefilter used to select the relevant nodes. nodeiterator.expandentityreferences read only is a boolean indicating if, when discarding an entityreference its whole sub-tree must be discarded at the same time. nodeiterator.referencenode read only returns the node to which the iterator is anchored. nodeiterator.pointerbeforereferencenode read only returns a boolean flag that indicates whether the nodeiterator is anchored before, the flag being true, or after, the flag being false, the anchor node. methods this interface doesn't inherit any method. nodeiterator.detach() this operation is a no-op. it doesn't do anything. previously it was telling the engine that the nodeiterator was no more used, but this ...
... is now useless. nodeiterator.previousnode() returns the previous node in the document, or null if there are none. nodeiterator.nextnode() returns the next node in the document, or null if there are none. specifications specification status comment domthe definition of 'nodeiterator' in that specification. living standard added the referencenode and pointerbeforereferencenode properties. removed the expandentityreferences property. the method detach() has been changed to be a no-op. the methods previousnode() and nextnode() don't raise an exception any more. document object model (dom) level 2 traversal and range specificationthe definition of 'nodeiterator' in that specification. obsolete initial definition. ...
Using the Notifications API - Web APIs
omething else with another application. many examples of this now exist, such as slack. we've written a real world example — a to-do list app — to give more of an idea of how web notifications can be used. it stores data locally using indexeddb and notifies users when tasks are due using system notifications. download the to-do list code, or view the app running live. requesting permission before an app can send a notification, the user must grant the application the right to do so. this is a common requirement when an api tries to interact with something outside a web page — at least once, the user needs to specifically grant that application permission to present notifications, thereby letting the user control which apps/sites are allowed to display notifications. because of abuses o...
...nippet. inside here we explicitly set the notification.permission value (some old versions of chrome failed to do this automatically), and show or hide the button depending on what the user chose in the permission dialog. we don't want to show it if permission has already been granted, but if the user chose to deny permission, we want to give them the chance to change their mind later on. note: before version 37, chrome doesn't let you call notification.requestpermission() in the load event handler (see issue 274284). feature-detecting the requestpermission() promise above we said that we had to check whether the browser supports the promise version of notification.requestpermission(). we did this using the following: function checknotificationpromise() { try { notification.reque...
PerformanceNavigationTiming.domComplete - Web APIs
example the following example illustrates this property's usage. ...
... example the following example illustrates this property's usage. ...
PerformanceNavigationTiming.domContentLoadedEventStart - Web APIs
example the following example illustrates this property's usage. ...
... example the following example illustrates this property's usage. ...
PerformanceNavigationTiming.domInteractive - Web APIs
example the following example illustrates this property's usage. ...
... example the following example illustrates this property's usage. ...
PerformanceNavigationTiming.loadEventStart - Web APIs
example the following example illustrates this property's usage. ...
... example the following example illustrates this property's usage. ...
PerformanceNavigationTiming.unloadEventStart - Web APIs
example the following example illustrates this property's usage. ...
... example the following example illustrates this property's usage. ...
PerformanceResourceTiming.connectStart - Web APIs
example in the following example, the value of the *start and *end properties of all "resource" type events are logged. ...
... example in the following example, the value of the *start and *end properties of all "resource" type events are logged. ...
PerformanceResourceTiming.domainLookupStart - Web APIs
example in the following example, the value of the *start and *end properties of all "resource" type events are logged. ...
... example in the following example, the value of the *start and *end properties of all "resource" type events are logged. ...
PerformanceResourceTiming.responseEnd - Web APIs
example in the following example, the value of the *start and *end properties of all "resource" type events are logged. ...
... example in the following example, the value of the *start and *end properties of all "resource" type events are logged. ...
PerformanceResourceTiming.secureConnectionStart - Web APIs
if a secure connection is not used, this property returns zero. example in the following example, the value of the *start and *end properties of all "resource" type events are logged. ...
...if a secure connection is not used, this property returns zero. example in the following example, the value of the *start and *end properties of all "resource" type events are logged. ...
PerformanceTiming - Web APIs
ned is 0. performancetiming.redirectend read only when the last http redirect is completed, that is when the last byte of the http response has been received. if there is no redirect, or if one of the redirects is not of the same origin, the value returned is 0. performancetiming.fetchstart read only when the browser is ready to fetch the document using an http request. this moment is before the check to any application cache. performancetiming.domainlookupstart read only when the domain lookup starts. if a persistent connection is used, or the information is stored in a cache or a local resource, the value will be the same as performancetiming.fetchstart. performancetiming.domainlookupend read only when the domain lookup is finished. if a persistent connection is used, o...
... is when its document.readystate changes to 'loading' and the corresponding readystatechange event is thrown. performancetiming.dominteractive read only when the parser finished its work on the main document, that is when its document.readystate changes to 'interactive' and the corresponding readystatechange event is thrown. performancetiming.domcontentloadedeventstart read only right before the parser sent the domcontentloaded event, that is right after all the scripts that need to be executed right after parsing have been executed. performancetiming.domcontentloadedeventend read only right after all the scripts that need to be executed as soon as possible, in order or not, have been executed. performancetiming.domcomplete read only when the parser finished its work on t...
PublicKeyCredentialRequestOptions.extensions - Web APIs
any extension. also chrome doesn't plan to support any other extension in future extension identifier type description appid usvstring fido appid. an appid which was used with legacy fido js apis to identify the current relying party. txauthsimple usvstring simple transaction authorization. this text is displayed on a prompt of the authenticator before verifying the user or testing their presence. the client outputs a usvstring which is the text as it was displayed (line breaks may have been added). txauthgeneric an object with two properties: contenttype (usvstring) content (arraybuffer) generic transaction authorization. this is used to display an image or some non-textual content on the authentica...
...ifying the user or testing their presence. the client outputs a usvstring which is the text as it was displayed (line breaks may have been added). txauthgeneric an object with two properties: contenttype (usvstring) content (arraybuffer) generic transaction authorization. this is used to display an image or some non-textual content on the authenticator before verifying the user or testing their presence. the contenttype gives the mime type of the resource to be displayed while content gives its actual content. the client outputs the hash of the content which was displayed (hashing with the same algorithm which is used for the signature). uvi boolean user verification index. if true, the client outputs an arraybuffer which contains a val...
RTCDataChannel.maxRetransmits - Web APIs
the default is null. ...
... giving up, as set when the data channel was created, or null, which indicates that there is no maximum. this can only be set when the rtcdatachannel is created by calling rtcpeerconnection.createdatachannel(), using the maxretransmits field in the specified options. syntax var tries = adatachannel.maxretransmits; value the maximum number of times the browser will try to retransmit a message before giving up, or null if not set when rtcpeerconnection.createdatachannel() was called. the default is null. example // tbd specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'rtcdatachannel.maxretransmits' in that specification. candidate recommendation initial specification. ...
Range() - Web APIs
Web › API › Range › Range
the range() constructor returns a newly created range object whose start and end is the global document object. syntax range = new range() example in this example we create a new range with the range() constructor, and set its beginning and end positions using the range.setstartbefore() and range.setendafter() methods. we then select the range using window.getselection() and selection.addrange(). ...
...nge.setstartbefore() and range.setendafter() methods. we then select the range using window.getselection() and selection.addrange(). html <p>first paragraph.</p> <p>second paragraph.</p> <p>third paragraph.</p> <p>fourth paragraph.</p> javascript const paragraphs = document.queryselectorall('p'); // create new range const range = new range(); // start range at second paragraph range.setstartbefore(paragraphs[1]); // end range at third paragraph range.setendafter(paragraphs[2]); // get window selection const selection = window.getselection(); // add range to window selection selection.addrange(range); result specification specification status comment domthe definition of 'range.range()' in that specification. living standard initial definition. ...
Range - Web APIs
Web › API › Range
thin which the range starts. range.startoffset read only returns a number representing where in the startcontainer the range starts. constructor range() returns a range object with the global document as its start and end. methods there are no inherited methods. range.setstart() sets the start position of a range. range.setend() sets the end position of a range. range.setstartbefore() sets the start position of a range relative to another node. range.setstartafter() sets the start position of a range relative to another node. range.setendbefore() sets the end position of a range relative to another node. range.setendafter() sets the end position of a range relative to another node. range.selectnode() sets the range to contain the node and its contents. range.select...
...o a new node. range.compareboundarypoints() compares the boundary points of the range with another range. range.clonerange() returns a range object with boundary points identical to the cloned range. range.detach() releases the range from use to improve performance. range.tostring() returns the text of the range. range.comparenode() returns a constant representing whether the node is before, after, inside, or surrounding the range. range.comparepoint() returns -1, 0, or 1 indicating whether the point occurs before, inside, or after the range. range.createcontextualfragment() returns a documentfragment created from a given string of code. range.getboundingclientrect() returns a domrect object which bounds the entire contents of the range; this would be the union of all the...
Selection - Web APIs
Web › API › Selection
f document order). the anchor is where the user began the selection and the focus is where the user ends the selection. if you make a selection with a desktop mouse, the anchor is placed where you pressed the mouse button, and the focus is placed where you released the mouse button. anchor and focus should not be confused with the start and end positions of a selection. the anchor can be placed before the focus or vice-versa, depending on the direction you made your selection. properties selection.anchornoderead only returns the node in which the selection begins. can return null if selection never existed in the document (e.g., an iframe that was never clicked on). selection.anchoroffsetread only returns a number representing the offset of the selection's anchor within the anchornod...
...able elements (e.g., <a>). the above behavior applies to selections made using the following methods: selection.collapse() selection.collapsetostart() selection.collapsetoend() selection.extend() selection.selectallchildren() selection.addrange() selection.setbaseandextent() and when the range is modified using the following methods: range.setstart() range.setend() range.setstartbefore() range.setstartafter() range.setendbefore() range.setendafter() range.collapse() range.selectnode() range.selectnodecontents() glossary other key terms used in this section. anchor the anchor of a selection is the beginning point of the selection. when making a selection with a mouse, the anchor is where in the document the mouse button is initially pressed. as the user changes the ...
Selection API - Web APIs
yessamsung internet android full support yescontainsnode experimentalchrome full support yesedge full support 12firefox full support 4notes full support 4notes notes before firefox 35, the method didn't throw if node was null.ie no support noopera full support yessafari full support yeswebview android full support yeschrome android full support ...
... yessafari full support yeswebview android full support yeschrome android full support yesfirefox android full support 4notes full support 4notes notes before firefox 35, the method didn't throw if node was null.opera android full support yessafari ios full support yessamsung internet android full support yesdeletefromdocument experimentalchrome full support yesedge ...
ServiceWorkerContainer.startMessages() - Web APIs
the startmessages() method of the serviceworkercontainer interface explicitly starts the flow of messages being dispatched from a service worker to pages under its control (e.g. sent via client.postmessage()). this can be used to react to sent messages earlier, even before that page's content has finished loading. ...
...ker to the page (using client.postmessage()) are queued while the page is loading, and get dispatched once the page's html document has been loaded and parsed (i.e. after the domcontentloaded event fires). it's possible to start dispatching these messages earlier by calling serviceworkercontainer.startmessages(), for example if you've invoked a message handler using eventtarget.addeventlistener() before the page has finished loading, but want to start processing the messages right away. note: the messages start being sent automatically when setting the handler directly using serviceworkercontainer.onmessage. in this you don't need startmessages(). syntax serviceworkercontainer.startmessages(); parameters none. return value undefined. examples if('serviceworker' in navigator) { navig...
Storage API - Web APIs
the storage standard defines a common, shared storage system to be used by all apis and technologies that store content-accessible data for individual web sites. the storage api gives sites' code the ability to find out how much space they can use, how much they are already using, and even control whether or not they need to be alerted before the user agent disposes of site data in order to make room for other things. note: this feature is available in web workers. site storage—the data stored for a web site which is managed by the storage standard—includes: indexeddb databases cache api data service worker registrations web storage api data managed using window.localstorage history state information saved using history.pushstate() application caches notification data other ki...
...ata 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 as needed. to change an origin's box mode requires permission to use the "persistent-storage" feature. data persistence and clearing if the site or app has the "persistent-storage" feature per...
Using readable streams - Web APIs
function readstream() { const reader = stream.getreader(); let charsreceived = 0; // read() returns a promise that resolves // when a value has been received reader.read().then(function processtext({ done, value }) { // result objects contain two properties: // done - true if the stream has already given you all its data. // value - some d...
......
Using writable streams - Web APIs
defaultwriter.ready .then(() => { defaultwriter.close(); }) .then(() => { console.log("all chunks written"); }) .catch((err) => { console.log("stream error:", err); }); } so here we create a writer to write the chunks to the stream using writablestream.getwriter(). this creates a writablestreamdefaultwriter instance. we also create...
...r something similarly bad). closing and aborting as mentioned above, we call the close() method when the writing is finished, which triggers the close() method specified inside the writablestream() constructor. we could also abort the stream by calling writablestreamdefaultwriter.abort(). the difference is that when close is called, any previously enqueued chunks are written and finished with before the stream is closed. when abort is called, any previously enqueued chunks are just thrown away immediately and then the stream is moved to an errored state. this also triggers any abort() method specified in the writablestream() constructor to be invoked. ...
TreeWalker - Web APIs
er, a node is visible if it exists in the logical view determined by the whattoshow and filter parameter arguments. (whether or not the node is visible on the screen is irrelevant.) treewalker.parentnode() moves the current node to the first visible ancestor node in the document order, and returns the found node. it also moves the current node to this one. if no such node exists, or if it is before that the root node defined at the object construction, returns null and the current node is not changed. treewalker.firstchild() moves the current node to the first visible child of the current node, and returns the found child. it also moves the current node to this child. if no such child exists, returns null and the current node is not changed. treewalker.lastchild() moves the current node...
...treewalker.nextsibling() moves the current node to its next sibling, if any, and returns the found sibling. if there is no such node, null is returned and the current node is not changed. treewalker.previousnode() moves the current node to the previous visible node in the document order, and returns the found node. it also moves the current node to this one. if no such node exists, or if it is before that the root node defined at the object construction, returns null and the current node is not changed. treewalker.nextnode() moves the current node to the next visible node in the document order, and returns the found node. it also moves the current node to this one. if no such node exists, returns null and the current node is not changed. specifications specification status ...
URL - Web APIs
Web › API › URL
in (that is the hostname) followed by (if a port was specified) a ':' and the port of the url. hostname a usvstring containing the domain of the url. href a stringifier that returns a usvstring containing the whole url. origin read only returns a usvstring containing the origin of the url, that is its scheme, its domain and its port. password a usvstring containing the password specified before the domain name. pathname a usvstring containing an initial '/' followed by the path of the url. port a usvstring containing the port number of the url. protocol a usvstring containing the protocol scheme of the url, including the final ':'. search a usvstring indicating the url's parameter string; if any parameters are provided, this string includes all of them, beginning with the leadin...
...ocol 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 can be used to access the individual query parameters found in search. username a usvstring containing the username specified before the 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, f...
URLUtilsReadOnly.hash - Web APIs
this has been fixed to match the spec.ie no support noopera no support nosafari no support nowebview android no support nochrome android no support ...
...this has been fixed to match the spec.opera android no support nosafari ios no support nosamsung internet android no support nolegend full support ...
URLUtilsReadOnly - Web APIs
this has been fixed to match the spec.ie no support noopera no support nosafari no support nowebview android no support nochrome android no support ...
...this has been fixed to match the spec.opera android no support nosafari ios no support nosamsung internet android no support nohost experimentalchrome no support no...
USBDevice.opened - Web APIs
Web › API › USBDevice › opened
what data can be passed to a usb device and how it is passed is particular and unique to each device. ...
... what data can be passed to a usb device and how it is passed is particular and unique to each device. ...
WebGLRenderingContext.compressedTexImage[23]D() - Web APIs
the webglrenderingcontext.compressedteximage2d() and webgl2renderingcontext.compressedteximage3d() methods of the webgl api specify a two- or three-dimensional texture image in a compressed format. compressed image formats must be enabled by webgl extensions before using these methods. syntax // webgl 1: void gl.compressedteximage2d(target, level, internalformat, width, height, border, arraybufferview? pixels); // additionally available in webgl 2: // read from buffer bound to gl.pixel_unpack_buffer void gl.compressedteximage2d(target, level, internalformat, width, height, border, glsizei imagesize, glintptr offset); void gl.compressedteximage2d(target, level, internalformat, width, height, border, arraybufferview srcdata, optional srcoffset, optional srclength...
..._negative_z: negative z face for a cube-mapped texture. possible values for compressedteximage3d: gl.texture_2d_array gl.texture_3d level a glint specifying the level of detail. level 0 is the base image level and level n is the nth mipmap reduction level. internalformat a glenum specifying the compressed image format. compressed image formats must be enabled by webgl extensions before using this method. all values are possible for compressedteximage2d. see compressed texture formats for which are valid for compressedteximage3d. possible values: when using the webgl_compressed_texture_s3tc extension: ext.compressed_rgb_s3tc_dxt1_ext ext.compressed_rgba_s3tc_dxt1_ext ext.compressed_rgba_s3tc_dxt3_ext ext.compressed_rgba_s3tc_dxt5_ext when using t...
WebGLRenderingContext.compressedTexSubImage2D() - Web APIs
the webglrenderingcontext.compressedtexsubimage2d() method of the webgl api specifies a two-dimensional sub-rectangle for a texture image in a compressed format. compressed image formats must be enabled by webgl extensions before using this method or a webgl2renderingcontext must be used. syntax // webgl 1: void gl.compressedtexsubimage2d(target, level, xoffset, yoffset, width, height, format, arraybufferview? pixels); // additionally available in webgl 2: void gl.compressedtexsubimage2d(target, level, xoffset, yoffset, width, height, format, imagesize, offset); void gl.compressedtexsubimage2d(target, level, xoffset, yoffset, width, height, format, arraybufferview srcdata, optional srcoffset, optional srclengthoverride); parameters target a glenum specifying the binding point (target...
...g the horizontal offset within the compressed texture image. yoffset a glint specifying the vertical offset within the compressed texture image. width a glsizei specifying the width of the compressed texture. height a glsizei specifying the height of the compressed texture. format a glenum specifying the compressed image format. compressed image formats must be enabled by webgl extensions before using this method. possible values: when using the webgl_compressed_texture_s3tc extension: ext.compressed_rgb_s3tc_dxt1_ext ext.compressed_rgba_s3tc_dxt1_ext ext.compressed_rgba_s3tc_dxt3_ext ext.compressed_rgba_s3tc_dxt5_ext when using the webgl_compressed_texture_s3tc_srgb extension: ext.compressed_srgb_s3tc_dxt1_ext ext.compressed_srgb_alpha_s3tc_d...
WebGLRenderingContext.disable() - Web APIs
deactivates blending of the computed fragment color values. see webglrenderingcontext.blendfunc(). gl.cull_face deactivates culling of polygons. see webglrenderingcontext.cullface(). gl.depth_test deactivates depth comparisons and updates to the depth buffer. see webglrenderingcontext.depthfunc(). gl.dither deactivates dithering of color components before they get written to the color buffer. gl.polygon_offset_fill deactivates adding an offset to depth values of polygon's fragments. see webglrenderingcontext.polygonoffset(). gl.sample_alpha_to_coverage deactivates the computation of a temporary coverage value determined by the alpha value. gl.sample_coverage deactivates anding the fragment's coverage...
... see webglrenderingcontext.scissor(). gl.stencil_test deactivates stencil testing and updates to the stencil buffer. see webglrenderingcontext.stencilfunc(). when using a webgl 2 context, the following values are available additionally: constant description gl.rasterizer_discard deactivates that primitives are discarded immediately before the rasterization stage, but after the optional transform feedback stage. gl.clear() commands are ignored. return value none. examples gl.disable(gl.dither); to check if a capability is disabled, use the webglrenderingcontext.isenabled() method: gl.isenabled(gl.dither); // false specifications specification status comment webgl 1.0the definition of 'd...
WebGLRenderingContext.enable() - Web APIs
lend activates blending of the computed fragment color values. see webglrenderingcontext.blendfunc(). gl.cull_face activates culling of polygons. see webglrenderingcontext.cullface(). gl.depth_test activates depth comparisons and updates to the depth buffer. see webglrenderingcontext.depthfunc(). gl.dither activates dithering of color components before they get written to the color buffer. gl.polygon_offset_fill activates adding an offset to depth values of polygon's fragments. see webglrenderingcontext.polygonoffset(). gl.sample_alpha_to_coverage activates the computation of a temporary coverage value determined by the alpha value. gl.sample_coverage activates anding the fragment's coverage with ...
... scissor rectangle. see webglrenderingcontext.scissor(). gl.stencil_test activates stencil testing and updates to the stencil buffer. see webglrenderingcontext.stencilfunc(). when using a webgl 2 context, the following values are available additionally: constant description gl.rasterizer_discard primitives are discarded immediately before the rasterization stage, but after the optional transform feedback stage. gl.clear() commands are ignored. return value none. examples gl.enable(gl.dither); to check if a capability is enabled, use the webglrenderingcontext.isenabled() method: gl.isenabled(gl.dither); // true specifications specification status comment webgl 1.0the definition of 'enab...
WebGLRenderingContext.isEnabled() - Web APIs
t description gl.blend blending of the computed fragment color values. see webglrenderingcontext.blendfunc(). gl.cull_face culling of polygons. see webglrenderingcontext.cullface(). gl.depth_test depth comparisons and updates to the depth buffer. see webglrenderingcontext.depthfunc(). gl.dither dithering of color components before they get written to the color buffer. gl.polygon_offset_fill adding an offset to depth values of polygon's fragments. see webglrenderingcontext.polygonoffset(). gl.sample_alpha_to_coverage computation of a temporary coverage value determined by the alpha value. gl.sample_coverage anding the fragment's coverage with the temporary coverage value. see ...
...ide of the scissor rectangle. see webglrenderingcontext.scissor(). gl.stencil_test stencil testing and updates to the stencil buffer. see webglrenderingcontext.stencilfunc(). when using a webgl 2 context, the following values are available additionally: constant description gl.rasterizer_discard primitives are discarded immediately before the rasterization stage, but after the optional transform feedback stage. gl.clear() commands are ignored. return value a glboolean indicating if the capability cap is enabled (true), or not (false). examples gl.isenabled(gl.stencil_test); // false to activate or deactivate a specific capability, use the webglrenderingcontext.enable() and webglrenderingcontext.disable() methods...
Basic scissoring - Web APIs
, 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 the webgl pipeline. the reason for this distinction is that fragment color (and other fragment values, such as depth) may be manipulated and changed several times during graphics operations before finally being written to the screen. we have already seen how fragment color changes during graphics operations, by applying color masking. in other cases, the fragments may be discarded altogether (so the pixel value is not updated), or it may interact with the already existing pixel value (such as when doing color blending for non-opaque elements in the scene). here we see another example of t...
...ases, the fragments may be discarded altogether (so the pixel value is not updated), or it may interact with the already existing pixel value (such as when doing color blending for non-opaque elements in the scene). here we see another example of the distinction between fragments and pixels. scissoring is a distinct stage in the webgl/opengl graphics pipeline (it occurs after color clearing, but before color masking). before the actual pixels are updated, fragments must go through the scissor test. if the fragments pass the scissor test, they continue down the graphics pipeline, and the corresponding pixels are updated on the screen. if they fail the test, they are immediately discarded, no further processing occurs, and pixels are not updated. because only fragments within the specified rectan...
Animating textures in WebGL - Web APIs
tetexture() function looks like; this is where the real work is done: function updatetexture(gl, texture, video) { const level = 0; const internalformat = gl.rgba; const srcformat = gl.rgba; const srctype = gl.unsigned_byte; gl.bindtexture(gl.texture_2d, texture); gl.teximage2d(gl.texture_2d, level, internalformat, srcformat, srctype, video); } you've seen this code before. it's nearly identical to the image onload function in the previous example — except when we call teximage2d(), instead of passing an image object, we pass in the <video> element. webgl knows how to pull the current frame out and use it as a texture. then in main() in place of the call to loadtexture() in the previous example, we call inittexture() followed by setupvideo() . in the definitio...
... except when we call teximage2d(), instead of passing an image object, we pass in the <video> element. webgl knows how to pull the current frame out and use it as a texture. then in main() in place of the call to loadtexture() in the previous example, we call inittexture() followed by setupvideo() . in the definition of render() if copyvideo is true, then we call updatetexture() each time just before we call the drawscene() function. const texture = inittexture(gl); const video = setupvideo('firefox.mp4'); var then = 0; // draw the scene repeatedly function render(now) { now *= 0.001; // convert to seconds const deltatime = now - then; then = now; if (copyvideo) { updatetexture(gl, texture, video); } drawscene(gl, programinfo, buffers, texture, d...
Using textures in WebGL - Web APIs
gl requires all samples of npot textures to fail by returning transparent black: rgba(0,0,0,0). to load the image, add a call to our loadtexture() function within our main() function. this can be added after the initbuffers(gl) call. // load texture const texture = loadtexture(gl, 'cubetexture.png'); mapping the texture onto the faces at this point, the texture is loaded and ready to use. but before we can use it, we need to establish the mapping of the texture coordinates to the vertices of the faces of our cube. this replaces all the previously existing code for configuring colors for each of the cube's faces in initbuffers(). const texturecoordbuffer = gl.createbuffer(); gl.bindbuffer(gl.array_buffer, texturecoordbuffer); const texturecoordinates = [ // front 0.0, 0.0, ...
...we tell webgl we want to a...
Using WebGL extensions - Web APIs
webgl, like its sister apis (opengl and opengl es), supports extensions. a complete list of extensions is available in the khronos webgl extension registry. note: in webgl, unlike in other gl apis, extensions are only available if explicitly requested. canonical extension names, vendor prefixes and preferences extensions may be supported by browser vendors before being officially ratified (but only when they are in draft stage). in that case, their name can be prefixed by the vendor prefix (moz_, webkit_, etc.) or the extension is only available once a browser preference has been toggled. if you wish to work with the bleeding edge of extensions, and want to keep working on upon ratification (assuming, of course, that the extension doesn't change in incompatible ways), that you query the can...
...for example: var float_texture_ext = gl.getextension('oes_texture_float'); the return value is null if the extension is not supported, or an extension object otherwise. extension objects if an extension defines specific symbols or functions that are not available in the core specification of webgl, they ...
WebGL best practices - Web APIs
be used to release a webgl context and its resources eagerly. use this if you are finished with any contexts, such as probe contexts, or if you hit a fallback case. flush when expecting results (like queries or rendering frame completion) flush tells the implementation to push all pending commands out for execution, flushing them out of the queue, instead of waiting for more commands to enqueue before sending for execution. for example, it is possible for the following to never complete without context loss: sync = glfencesync(gl_sync_gpu_commands_complete, 0); glclientwaitsync(sync, 0, gl_timeout_ignored); webgl doesn't have a swapbuffers call by default, so a flush can help fill the gap, as well. use webgl.flush() when not using requestanimationframe when not using raf, (such as when u...
...ternal_tex_tranform_prog) <pipeline flush> +bindframebuffer(webgl_texture._internal_framebuffer) +bindtexture(htmlvideoelement._internal_video_tex) +drawarrays() // y-flip/colorspace-transform/alpha-(un)premultiply +bindtexture(webgl_texture) +bindframebuffer(target) +useprogram(prog1) <pipeline flush> drawarrays() ... prefer doing uploads before starting drawing, or at least between pipelines: in webgl: ... bindtexture(webgl_texture) teximage2d(htmlvideoelement) useprogram(prog1) <pipeline flush> bindframebuffer(target) drawarrays() bindtexture(webgl_texture) drawarrays() ... behind the scenes in the browser: ... bindtexture(webgl_texture) -teximage2d(htmlvideoelement): +usepro...
WebGL model view projection - Web APIs
ace of the model as well. in this case, for every frame of the animation a series of scale, rotation, and translation matrices move the data into the desired spot in clip space. the cube is the size of clip space (-1,-1,-1) to (1,1,1) so it will need to be shrunk down in order to not fill the entirety of clip space. this matrix is sent directly to the shader, having been multiplied in javascript beforehand. the following code sample defines a method on the cubedemo object that will create the model matrix. it uses custom functions to create and multiply matrices as defined in the mdn webgl shared code. the new function looks like this: cubedemo.prototype.computemodelmatrix = function(now) { //scale down by 50% var scale = mdn.scalematrix(0.5, 0.5, 0.5); // rotate a slight tilt var ro...
...tical, the important step here is in the vertex shader. rather than modifying the vertex directly, it gets multiplied by an additional projection matrix, which (as the name suggests) projects 3d points onto a 2d drawing surface: // make sure to read the transformations in reverse order gl_position = projection * model * vec4(position, 1.0); the results view on jsfiddle the viewing frustum before we move on to covering how to compute a perspective projection matrix, we need to introduce the concept of the viewing frustum (also known as the view frustum). this is the region of space whose contents are visible to the user at the current time. it's the 3d region of space defined by the field of view and the distances specified as the nearest and farthest content that should be rendered. whi...
WebRTC connectivity - Web APIs
eavy rewriting for structural integrity and content completeness. lots of info here is good but the organization is a mess since this is sort of a dumping ground right now. signaling unfortunately, webrtc can’t create connections without some sort of server in the middle. we call this the signal channel or signaling service. it’s any sort of channel of communication to exchange information before setting up a connection, whether by email, post card or a carrier pigeon... it’s up to you. the information we need to exchange is the offer and answer which just contains the sdp mentioned below. peer a who will be the initiator of the connection, will create an offer. they will then send this offer to peer b using the chosen signal channel. peer b will receive the offer from the signal chan...
...otocol set to udp) can be one of these types: host a host candidate is one for which its ip address is the actual, direct ip address of the remote peer. prflx a peer reflexive candidate is one whose ip address comes from a symmetric nat between the two peers, usually as an additional candidate during trickle ice (that is, additional candidate exchanges that occur after primary signaling but before the connection verification phase is finished). srflx a server reflexive candidate is generated by a stun/turn server; the connection's initiator requests a candidate from the stun server, which forwards the request through the remote peer's nat, which creates and returns a candidate whose ip address is local to the remote peer. the stun server then replies to the initiator's request with a can...
Signaling and video calling - Web APIs
ment's srcobject property. since the element is configured to automatically play incoming video, the stream begins playing in our local preview box. we then iterate over the tracks in the stream, calling addtrack() to add each track to the rtcpeerconnection. even though the connection is not fully established yet, you can begin sending data when you feel it's appropriate to do so. media received before the ice negotiation is completed may be used to help ice decide upon the best connectivity approach to take, thus aiding in the negotiation process. note that for native apps, such as a phone application, you should not begin sending until the connection has been accepted at both ends, at a minimum, to avoid inadvertently sending video and/or audio data when the user isn't prepared for it. as s...
......
WebRTC API - Web APIs
the documentation you'll find here will help you understand the fundamentals of webrtc, how to set up and use both data and media connections, and more. interoperability because implementations of webrtc are still evolving, and because each browser has different levels of support for codecs and webrtc features, you should strongly consider making use of the adapter.js library provided by google before you begin to write your code. adapter.js uses shims and polyfills to smooth over the differences among the webrtc implementations across the environments supporting it. adapter.js also handles prefixes and other naming differences to make the entire webrtc development process easier, with more broadly compatible results. the library is also available as an npm package. to learn more about adapt...
...he amount of data currently buffered by the data channel—as indicated by its bufferedamount property—has decreased to be at or below the channel's minimum buffered data size, as specified by bufferedamountlowthreshold. close the data channel has completed the closing process and is now in the closed state. its underlying data transport is completely closed at this point. you can be notified before closing completes 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 ava...
Using bounded reference spaces - Web APIs
t solution is to just treat the each boundary segment as if it were an object to hit test against. as the user grows close to the boundary, you might warn them by displaying a message, flashing a warning indicator, playing an audio warning, or the like. and if the user actually collides with the boundary, don't let them continue past it. <<<--- example --->>> creating a bounded reference space before creating a project that relies on bounded reference spaces, it's important to keep in mind that not all xr devices are capable of creating them. by their very nature, bounded reference spaces have special hardware requirements, since they need to allow for the user to physically move around in space while their movements are tracked. in this section, we'll look at how to safely create a session t...
...l xr devices are capable of creating them. by their very nature, bounded reference spaces have special hardware requirements, since they need to allow for the user to physically move around in space while their movements are tracked. in this section, we'll look at how to safely create a session that will work whether bounded spaces are supported or not. safely creating a bounded-preferred space before actually attempting to create a bounded reference space, you need to create a session that supports them. since not all hardware supports 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. you can create a session that supports a bounded-...
Viewpoints and viewers: Simulating cameras in WebXR - Web APIs
nce, mathematics, art, graphic design, kinematics, anatomy, physiology, physics, and cinematography. since we don't have a real camera, we imagine one, reproducing the effect of having a camera, without actually having the ability to move the user around the scene. there are a few articles about the fundamental math, geometry, and other concepts behind webgl and webxr which may be useful to read before or while reading this one, including: explaining basic 3d theory matrix math for the web webgl model view projection geometry and reference spaces in webxr ed. note: most diagrams used in this article to show how the camera moves while performing standard movements was taken from an article on the filmmakeriq web site; namely, from this image which is found all over the web, however, and ...
...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 that the action remains visible even though the game level is much larger than the viewport. positioning the camera since there are no standard camera objects in webgl or webxr, we need to simulate the camera ourselves. before we can do so, and before we can then simulate the movement of the camera, let's actually take a look at the virtual camera and how it can move, at the most fundamental level. as in all things, the position of an object in space—even if that space if virtual—can be represented using three numbers that indicate its position relative to the origin, whose position is defined to be (0, 0, 0). the...
Geometry and reference spaces in WebXR - Web APIs
, orientations, and movement of objects in virtual space—plus the need to integrate the human viewer of the scene into the mix—a thorough introduction to geometry and the use of matrices and vectors to manage 3d representations of a scene is well beyond the scope of what can be accomplished in this article. you can learn more about the individual operations in matrix math for the web. units before discussing the details of the geometry of the 3d space used by webxr, it's first useful to understand the units of measure that are applied to the 3d world. lengths and distances webgl measures all distances and lengths in meters. webxr inherits this standard, as well as the fact that the world is a cube two meters wide, two meters tall, and two meters deep. each of the three axes has a minimum...
...ion. xr sessions are created using the navigator.xr.requestsession() method. one of its optional parameters is an object conforming to the xrsessioninit dictionary which you can use to specify required and/or optional features that the session must (or should ideally) support. currently, the only supported options are strings identifying the standard reference spaces. using these, you can ensure before your code even runs that you have access to a webxr session that can support the reference space type you require or prefer. note: at this time, the reference space to use or to prefer is the only option available when creating an xrsession. in the future, it's likely that more options will become available. <<<--- insert table of reference space requirements here --->>> positioning and orie...
Lighting a WebXR setting - Web APIs
ible, a scene must include lighting of some sort, so all or nearly all scenes will have at least one light source and may have a great many of them. each light source substantially increases the amount of calculation needed to determine the final color and brightness of each displayed pixel. performing the shading for each of these light source types is more computationally demanding than the one before it; so ambient light is the least expensive to apply, followed by directional light sources, point lights, and finally spotlights. additionally, the more accurate the lighting is designed to be, the more computationally expensive it becomes. increased shadow detail, volumetric light (that is, lighting that you can see in the air, such as sunbeams or the beams of spotlights in the sky), and other...
... own vertex and fragment shaders. for each polygon in the scene, the vertex shader program determines the vertices' colors, and then the fragment shader generates each pixel in the polygon by combining the appropriate texel from the assigned texture, any color tint or effect, and other visual data. it is at this time that the scene's lighting is considered and applied as appropriate to the pixel before the pixel is stored into the framebuffer. the color of each pixel in the final, rendered, scene is calculated using some intricate math that factors in things like: the color of the texture element (the pixel within the texture mapped onto the object; also known as a texel) corresponding to the screen pixel, given the object geometry, the viewer position and orientation relative to each polyg...
Using the Web Animations API - Web APIs
ilable by default in firefox 48+ and chrome 36+. safari supports web animations in its technology preview version and there is also a handy polyfill that tests for feature support and adds it where necessary. writing css animations with the web animations api one of the more familiar ways to approach learning the web animations api is to start with something most web developers have played with before: css animations. css animations have a familiar syntax that breaks down nicely for demonstration purposes. the css version here’s a tumbling animation written in css showing alice falling down the rabbit hole that leads to wonderland (see the full code on codepen): notice that the background moves, alice spins, and her color changes at an offset from her spinning. we’re going to focus on...
...k closer at the cupcake’s animation: var nommingcake = document.getelementbyid('eat-me_sprite').animate( [ { transform: 'translatey(0)' }, { transform: 'translatey(-80%)' } ], { fill: 'forwards', easing: 'steps(4, end)', duration: alicechange.effect.timing.duration / 2 }); the element.animate() method will immediately run after it is called. to prevent the cake from eating itself up before the user has had the chance to click on it, we call animation.pause() on it immediately after it is defined, like so: nommingcake.pause(); we can now use the animation.play() method to run it whenever we’re ready: nommingcake.play(); specifically, we want to link it to alice’s animation, so she gets bigger as the cupcake gets eaten. we can achieve this via the following function: var gro...
Background audio processing using AudioWorklet - Web APIs
audio application is the topic of this article. it's worth noting that because audio processing can often involve substantial computation, your processor may benefit greatly from being built using webassembly, which brings near-native or fully native performance to web apps. implementing your audio processing algorithm using webassembly can make it perform markedly better. high level overview before we start looking at the use of audioworklet on a step-by-step basis, let's start with a brief high-level overview of what's involved. create module that defines a audio worklet processor class, based on audioworkletprocessor which takes audio from one or more incoming sources, performs its operation on the data, and outputs the resulting audio data. access the audio context's audioworklet thr...
... node, then use your audio pipeline as usual. throughout the remainder of this article, we'll look at these steps in more detail, with examples (including working examples you can try out on your own). the example code found on this page is derived from this working example which is available on glitch. the example creates an oscillator node and adds white noise to it using an audioworkletnode before playing the resulting sound out. slider controls are available to allow controlling the gain of both the oscillator and the audio worklet's output. glitch project page see the code try it live creating an audio worklet processor fundamentally, an audio worklet processor (which we'll refer to usually as either an "audio processor" or simply as a "processor" because otherwise this article wi...
Using the Web Speech API - Web APIs
her grammars available in the list (can be from 0 to 1 inclusive.) the added grammar is available in the list as a speechgrammar object instance. speechrecognitionlist.addfromstring(grammar, 1); we then add the speechgrammarlist to the speech recognition instance by setting it to the value of the speechrecognition.grammars property. we also set a few other properties of the recognition instance before we move on: speechrecognition.continuous: controls whether continuous results are captured (true), or just a single result each time recognition is started (false). speechrecognition.lang: sets the language of the recognition. setting this is good practice, and therefore recommended. speechrecognition.interimresults: defines whether the speech recognition system should return interim results...
...te('data-lang', voices[i].lang); option.setattribute('data-name', voices[i].name); voiceselect.appendchild(option); } } when we come to run the function, we do the following. this is because firefox doesn't support speechsynthesis.onvoiceschanged, and will just return a list of voices when speechsynthesis.getvoices() is fired. with chrome however, you have to wait for the event to fire before populating the list, hence the if statement seen below. populatevoicelist(); if (speechsynthesis.onvoiceschanged !== undefined) { speechsynthesis.onvoiceschanged = populatevoicelist; } speaking the entered text next, we create an event handler to start speaking the text entered into the text field. we are using an onsubmit handler on the form so that the action happens when enter/return is p...
Window.requestAnimationFrame() - Web APIs
the window.requestanimationframe() method tells the browser that you wish to perform an animation and requests that the browser calls a specified function to update an animation before the next repaint. the method takes a callback as an argument to be invoked before the repaint. note: your callback routine must itself call requestanimationframe() if you want to animate another frame at the next repaint. you should call this method whenever you're ready to update your animation onscreen. this will request that your animation function be called before the browser performs the next repaint. the number of callbacks is usually 60 times per second, but will generally match the display refresh rate in most web browsers as per w3c recommendation. requestanimationframe() calls are paused in most brows...
....min()` is used here to make sure that the element stops at exactly 200px. element.style.transform = 'translatex(' + math.min(0.1 * elapsed, 200) + 'px)'; if (elapsed < 2000) { // stop the animation after 2 seconds window.requestanimationframe(step); } } window.requestanimationframe(step); notes edge versions below 17 and internet explorer do not reliably fire requestanimationframe before the paint cycle. specification specification status comment html living standardthe definition of 'requestanimationframe' in that specification. living standard no change, supersedes the previous one. timing control for script-based animationsthe definition of 'requestanimationframe' in that specification. obsolete initial definition ...
WindowEventHandlers.onafterprint - Web APIs
in general, you should prefer the use of an @media print css at-rule, but it may be necessary to use these events in some cases. ...
...in general, you should prefer the use of an @media print css at-rule, but it may be necessary to use these events in some cases. ...
WindowEventHandlers - Web APIs
and not an interface; you can't actually create an object of type windoweventhandlers. properties the events properties, of the form onxyz, are defined on the windoweventhandlers, and implemented by window, and workerglobalscope for web workers. windoweventhandlers.onafterprint is an eventhandler representing the code to be called when the afterprint event is raised. windoweventhandlers.onbeforeprint is an eventhandler representing the code to be called when the beforeprint event is raised. windoweventhandlers.onbeforeunload is an eventhandler representing the code to be called when the beforeunload event is raised. windoweventhandlers.onhashchange is an eventhandler representing the code to be called when the hashchange event is raised. windoweventhandlers.onlanguagechange is a...
... ...
WindowOrWorkerGlobalScope.queueMicrotask() - Web APIs
the queuemicrotask() method, which is exposed on the window or worker interface, queues a microtask to be executed at a safe time prior to control returning to the browser's event loop. the microtask is a short function which will run after the current task has completed its work and when there is no other code waiting to be run before control of the execution context is returned to the browser's event loop. this lets your code run without interfering with any other, potentially higher priority, code that is pending, but before the browser regains control over the execution context, potentially depending on work you need to complete. you can learn more about how to use microtasks and why you might choose to do so in our microtask guide. the importance of microtasks comes in its ability to per...
...you can learn more about how to use microtasks and why you might choose to do so in our microtask guide. the importance of microtasks comes in its ability to perform tasks asynchronously but in a specific order. see using microtasks in javascript with queuemicrotask() for more details. microtasks are especially useful for libraries and frameworks that need to perform final cleanup or other just-before-rendering tasks. queuemicrotask() is exposed on the windoworworkerglobalscope mixin. syntax scope.queuemicrotask(function); parameters function a function to be executed when the browser engine determines it is safe to call your code. enqueued microtasks are executed after all pending tasks have completed but before yielding control to the browser's event loop. return value undefined.
WritableStream.WritableStream() - Web APIs
onous, it can return a promise to signal success or failure. the reason parameter contains a domstring describing why the stream was aborted. queuingstrategy optional an object that optionally defines a queuing strategy for the stream. this takes two parameters: highwatermark a non-negative integer — this defines the total number of chunks that can be contained in the internal queue before backpressure is applied. size(chunk) a method containing a parameter chunk — this indicates 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 ...
... defaultwriter.ready .then(() => { defaultwriter.close(); }) .then(() => { console.log("all chunks written"); }) .catch((err) => { console.log("stream error:", err); }); } const decoder = new textdecoder("utf-8"); const queuingstrategy = new countqueuingstrategy({ highwatermark: 1 }); let result = ""; const writablestream = new writa...
WritableStreamDefaultWriter.close() - Web APIs
the close() method of the writablestreamdefaultwriter interface closes the associated writable stream. the underlying sink will finish processing any previously-written chunks, before invoking the close behavior. during this time any further attempts to write will fail (without erroring the stream). syntax var promise = writablestreamdefaultwriter.close(); parameters none. return value a promise, which fulfills with the undefined if all remaining chunks were successfully written before the close, or rejects with an error if a problem was encountered during the process. exceptions typeerror the stream you are trying to close is not a writablestream. examples the following example shows the creation of a writablestream with a custom sink and an api-supplied queuing strategy. it...
... defaultwriter.ready .then(() => { defaultwriter.close(); }) .then(() => { console.log("all chunks written"); }) .catch((err) => { console.log("stream error:", err); }); } const decoder = new textdecoder("utf-8"); const queuingstrategy = new countqueuingstrategy({ highwatermark: 1 }); let result = ""; const writablestream = new writa...
WritableStreamDefaultWriter.ready - Web APIs
s when the desired size of the stream's internal queue transitions from non-positive to positive, signaling that it is no longer applying backpressure. syntax var promise = writablestreamdefaultwriter.ready; value a promise. example the following example shows two uses of the ready property. the first uses ready to ensure that the writablestream is done writing and thus able to receive data before sending a binary chunk. the second also checks whether the the writablestream is done writing, but this time because the writing must be finished before the writer can be closed. function sendmessage(message, writablestream) { // defaultwriter is of type writablestreamdefaultwriter var defaultwriter = writablestream.getwriter(); var encoder = new textencoder(); var encoded = encoder.enco...
... // make sure the stream and its writer are able to // receive data. defaultwriter.ready .then(function() { defaultwriter.write(chunk) .then(function() { console.log("chunk written to sink.); }) .catch(function(err) { console.log("chunk error: " + err); }); }); // call ready again to ensure that all chunks are written // before closing the writer. defaultwriter.ready .then(function() { defaultwriter.close() .then(function() { console.log("all chunks written"); }) .catch(function(err) { console.log("stream error: " + err); }); }); }); } specifications specification status comment streamsthe definition of 'ready' in that specification. ...
WritableStreamDefaultWriter.write() - Web APIs
te simply that the chunk has been accepted, and not necessarily that it is safely saved to its ultimate destination. syntax var promise = writablestreamdefaultwriter.write(chunk); parameters chunk a block of binary data to pass to the writablestream. return value a promise, which fulfills with the undefined upon a successful write, or rejects if the write fails or stream becomes errored before the writing process is initiated. exceptions typeerror the target stream is not a writable stream, or it does not have an owner. examples the following example shows the creation of a writablestream with a custom sink and an api-supplied queuing strategy. it then calls a function called sendmessage(), passing the newly created stream and a string. inside this function it calls the stream'...
... defaultwriter.ready .then(() => { defaultwriter.close(); }) .then(() => { console.log("all chunks written"); }) .catch((err) => { console.log("stream error:", err); }); } const decoder = new textdecoder("utf-8"); const queuingstrategy = new countqueuingstrategy({ highwatermark: 1 }); let result = ""; const writablestream = new writa...
XMLHttpRequest.withCredentials - Web APIs
uld be made using credentials such as cookies, authorization headers or tls client certificates. setting withcredentials has no effect on same-site requests. in addition, this flag is also used to indicate when cookies are to be ignored in the response. the default is false. xmlhttprequest from a different domain cannot set cookie values for their own domain unless withcredentials is set to true before making the request. the third-party cookies obtained by setting withcredentials to true will still honor same-origin policy and hence can not be accessed by the requesting script through document.cookie or from response headers. note: this never affects same-site requests. note: xmlhttprequest responses from a different domain cannot set cookie values for their own domain unless withcredenti...
.... the third-party cookies obtained by setting withcredentials to true will still honor same-origin policy and hence can not be accessed by the requesting script through document.cookie or from response headers. note: this never affects same-site requests. note: xmlhttprequest responses from a different domain cannot set cookie values for their own domain unless withcredentials is set to true before making the request, regardless of access-control- header values. example var xhr = new xmlhttprequest(); xhr.open('get', 'http://example.com/', true); xhr.withcredentials = true; xhr.send(null); specifications specification status comment xmlhttprequest living standard whatwg living standard ...
XMLHttpRequestEventTarget.onprogress - Web APIs
event event.loaded the amount of data currently transfered. event.total the total amount of data to be transferred. ...
... event event.loaded the amount of data currently transfered. event.total the total amount of data to be transferred. ...
XRReferenceSpace: reset event - Web APIs
he position or orientation of objects oriented using the reference space. this is common when the user calibrates or recalibrates an xr device, or if the device automatically changes its origin after losing tracking of the user, then re-gaining it. in the case of xrboundedreferencespace objects, the reset event can also be fired when the boundsgeometry changes. in either case, the event is sent before any webxr animation frames which make use of the new origin are executed. bubbles yes cancelable no interface xrreferencespaceevent event handler property onreset usage notes the reset event indicates that the coordinate system has been reset or reconfigured by changing the reference space's origin, moving and rotating it as indicated by th...
...e new origin are executed. bubbles yes cancelable no interface xrreferencespaceevent event handler property onreset usage notes the reset event indicates that the coordinate system has been reset or reconfigured by changing the reference space's origin, moving and rotating it as indicated by the event's transform property. the event is sent before any animation frame callbacks are executed to render the pending frame, to ensure that those callbacks have the updated coordinate system available. there are a number of reasons why a reset might occur. most common among them are the following: the user has manually reset the coordinate system, such as by requesting that the headset recalibrate itself to ensure that the facing direction and ...
XRSession.requestAnimationFrame() - Web APIs
this can be done from within the callback itself. ...
...ties between these methods and the global requestanimationframe() function provided by the window interface, you must not treat these as interchangeable. there is no guarantee that the latter will work at all while an immersive xr session is underway. syntax requestid = xrsession.requestanimationframe(animationframecallback); parameters animationframecallback a function which is called before the next repaint in order to allow you to update and render the xr scene based on elapsed time, animation, user input changes, and so forth. the callback receives as input two parameters: time a domhighrestimestamp indicating the time offset at which the updated viewer state was received from the webxr device. xrframe an xrframe object describing the state of the objects being tracked ...
XRSession - Web APIs
Web › API › XRSession
t handler property. select an event of type xrinputsourceevent which is sent to the session when one of the session's input sources has successfully completed a primary action. this generally corresponds to the user pressing a trigger, touchpad, or button, speaks a command, or performs a recognizable gesture. the select event is sent after the selectstart event is sent and immediately before the selectend event is sent. if select is not sent, then the select action was aborted before being completed. also available through the onselect event handler property. selectend an event of type xrinputsourceevent which gets sent to the session object when one of its input devices finishes its primary action or gets disconnected while in the process of handling a primary action...
...ction to begin. this is the first of the session* event to be sent. also available through the onselectstart event handler property. squeeze an xrinputsourceevent sent to indicate that a primary squeeze action has successfully completed. this indicates that the device being squeezed has been released, and may represent dropping a grabbed object, for example. it is sent immediately before the squeezeend event is sent to indicate that the squeeze action is over. also available through the onsqueeze event handler property. squeezeend an xrinputsourceevent sent to the xrsession when the primary squeeze action ends, whether or not the action was successful. also available using the onsqueezeend event handler property. squeezestart an event of type xrinp...
ARIA Test Cases - Accessibility
pass - - orca - - - - button basic button button with description dojo nightly build -- lots of other types of buttons there as well. expected at behavior: when focus falls on a button, a screen reader speaks the text of the button plus alternative text of any images within the button (the accessible name of the button). the word "button" is also spoken before or after the accessible name. markup used: notes: results: at firefox ie opera safari jaws 9 - - n/a n/a jaws 10 pass in non-v-pc mode, pass in v-pc-mode also if the button's text is not provided via labelledby or label. - - - voiceover (leopard) n/a n/a - fail window-eyes - - - - ...
... nvda - n/a - - zoom (leopard) pass n/a pass pass zoomtext - - - - orca - - - - aria-atomic="true" aria-atomic="true" aria-live="polite" expected at behavior: (al) for any changed text within an atomic live region, the screen reader should read the entire atomic region. (al) if two or more changes occur before the screen reader gets a chance to read the region, the screen reader should still only read the entire region once. (al) the screen reader should try to concatenate several sequential changes to the same region. if two changes occur almost at the same time (say within .05 seconds for example), the screen reader should make sure to read the entire region only once. markup used: aria-atomic=...
ARIA: Comment role - Accessibility
amples in the following example we have a document section that has been commented. the commented section is marked up using <span role="mark">. the related comment is marked up using an html structure wrapped with a <div> containing role="comment". ...
...nted text with an element containing the aria-details attribute, the value of which should be the id of the comment. ...
ARIA: feed role - Accessibility
d be scrolled into view when it, or a descendant element, receives focus. if the addition of articles occupies the main browser thread, make sure to set aria-busy="true" on the feed itself, and make sure to set it back to false when processing ends, or the user may not see the updates. to ensure good user experience, avoid inserting or removing articles in the middle of a feed, load new articles before the user has reached the end of the feed, and provide keyboard commands for moving focus among articles so that keyboard users can navigate through your feed. see keyboard interactions below. if the number of articles is known, set aria-setsize on the articles themselves. however, if the total number is extremely large, indefinite, or changes often, set aria-setsize="-1" to indicate that the siz...
...in the context of a feed, assistive technologies with a reading mode are responsible for: indicating which article contains the reading cursor by ensuring the article element or one of its descendants has dom focus. providing reading mode keys that move dom focus to the next and previous articles. providing reading mode keys for moving the reading cursor and dom focus past the end and before the start of the feed. keyboard interaction supporting the following, or a similar, interface is recommended when focus is inside the feed: page down: move focus to next article. page up: move focus to previous article. control + end: move focus to the first focusable element after the feed. control + home: move focus to the first focusable element before the feed. if a feed is n...
ARIA: checkbox role - Accessibility
e checked or unchecked status of the element. ...
...an 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 preferences</label> css [role="checkbox"] { padding:5px; } [aria-checked="true"]::before { content: "[x]"; } [aria-checked="false"]::before { content: "[ ]"; } javascript function changecheckbox(event) { let item = document.getelementbyid('chkpref'); switch(item.getattribute('aria-checked')) { case "true": item.setattribute('aria-checked', "false"); break; case "false": item.setattribute('aria-checked', "true"); break; } } accessibility concerns whe...
ARIA: textbox role - Accessibility
instead of using aria-placeholder, use the semantic <input type="text"> or <textarea> with a placeholder attribute. aria-readonly attribute indicates that the user cannot modify the value of the text field. instead of using aria-readonly, use the semantic <input type="text"> or <textarea> with a readonly attribute. aria-required attribute indicates that a value must be provided for the field before it is submitted. instead of using aria-required, use the semantic <input type="text"> or <textarea> with a required attribute. keyboard interactions in a single-line use (when aria-multiline is false or not used), the return or enter key submits the form. in a multi-line use (when aria-multiline is true), return or enter key inserts a line break. javascript features all features associated w...
...l features associated with any and all properties and states must be maintained, and forms submission on enter or return on a single line textbox needs to be handled. focus event handler and aria-activedescendent attribute if you are implementing a composite widget, such as a combobox composed of a text box and a listbox, you need to manage the aria-activedescendent attribute using a handler. before using this technique, ensure that the browsers you need to target currently support it. see the specification of aria-descendent for further information. it is a better 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. possi...
Keyboard-navigable JavaScript widgets - Accessibility
focusable by script, but it does not become part of the keyboard focus order. the order in which elements gain focus when using a keyboard, is the source order by default. in exceptional circumstances, authors may want to redefine the order. to do this, authors can set tabindex to any positive number. warning: avoid using positive values for tabindex. elements with a positive tabindex are put before the default interactive elements on the page, which means page authors will have to set (and maintain) tabindex values for all focusable elements on the page whenever they use one or more positive values for tabindex. the following table describes tabindex behavior in modern browsers: tabindex attribute focusable with mouse or javascript via element.focus() tab navigable ...
...elative to element's position in document (note that interactive elements like <a> have this behavior by default, they don't need the attribute). positive (e.g. tabindex="33") yes tabindex value determines where this element is positioned in the tab order: smaller values will position elements earlier in the tab order than larger values (for example, tabindex="7" will be positioned before tabindex="11"). non-native controls native html elements that are interactive, like <a>, <input> and <select>, are already accessible by keyboards, so to use one of them is the fastest path to make components work with keyboards. authors can also make a <div> or <span> keyboard accessible by adding a tabindex of 0. this is particularly useful for components that use interactive elements ...
Web Accessibility: Understanding Colors and Luminance - Accessibility
pts to creating accessible web content with color. luminance is of particular importance, however, because at the end of the day, understanding of what it is and how it is employed enables accessibility for those who are color-blind, as well as those who can perceive color. it is the luminance contrast that enable the color-blind to distinguish dark against light. luminance must be established before the contrast may be. when speaking of color contrast, w3c formulas are actually incorporating luminance, not just the colors ("hues") themselves. terminology can be confusing, because different terms are often used to describe the same thing. "luminance" and "saturation" are particularly important to get right. for example, "saturation" is known as "chroma" in some circles. in others, "chroma...
...both the rgb hexidecimal and css function syntax. a great example of a tool that converts colors for you is tom jewett's "mini color selector" with hsl, rgb, hex options for checking contrast in the browser. luminance and contrast contrast contrast between colors ("hues") is a critical component, but the use of color ("hues") alone is not enough to create accessible content. as mentioned before, any calculation of contrast must include luminance in the calculation. 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, ...
Understandable - Accessibility
when a control or other page feature receives focus, it should not change the context in a way that may confuse or disorientate the user. this is a matter of sensible design — people don't want interfaces to surprise them; they want things to be intuitive and behave as expected. for example, focusing a navigation menu option should not change the displayed page — it should be activated before the display changes. globaleventhandlers.onfocus contains some useful information. also see building keyboard accessibility back in for some useful implementation ideas. 3.2.2 on input (a) when data is inputted into a control, or a setting is changed, context should not be changed unexpectedly. the user should be warned/advised of the impending change before it occurs. ...
...ncial, data) (aa) in the case of forms involved with entry of sensitive data (such as legal agreements, e-commerce transactions, or personal data), at least one of the following should be true: submissions are reversible. data is checked for errors, and the user is given an opportunity to correct them. a mechanism is available for confirming and correcting information before final submission. reversible — for any view where data can be entered, provide an equivalent view that allows you to edit or even delete an entry, as appropriate. checking data — as covered in 3.3.1, a combination of client-side and server-side validation should be used to detect errors and display helpful messages to the user to allow them to correct their inputs. ...
-moz-user-focus - CSS: Cascading Style Sheets
ox, and that element is what receives focus. you can stop the textbox from taking keyboard focus by setting its tab index to -1, and from taking mouse focus by preventing the default action of mousedown events. syntax values ignore the element does not accept the keyboard focus and will be skipped in the tab order. normal the element can accept the keyboard focus. ...
...element does not accept the keyboard focus and will be skipped in the tab order. normal the element can accept the keyboard focus. select-after ? select-before ? select-menu ? select-same ? select-all ? none ? formal definition initial valuenoneapplies toall elementsinheritednocomputed valueas specifiedanimation typediscrete formal syntax ignore | normal | select-after | select-before | select-menu | select-same | select-all | none examples html <input class="ignored" value="the user cannot focus on this element."> css .ignored { -moz-user-focus: ignore; } specifications not part of any standard. a similar property, user-focus, was proposed in early drafts of a predecessor of the css3 ui specification, but was rejected by the working group. ...
::after (:after) - CSS: Cascading Style Sheets
Web › CSS › ::after
in css, ::after creates a pseudo-element that is the last child of the selected element. it is often used to add cosmetic content to an element with the content property. it is inline by default. /* add an arrow after links */ a::after { content: "→"; } note: the pseudo-elements generated by ::before and ::after are contained by the element's formatting box, and thus don't apply to replaced elements such as <img>, or to <br> elements. syntax /* css3 syntax */ ::after /* css2 syntax */ :after note: css3 introduced the ::after notation (with two colons) to distinguish pseudo-classes from pseudo-elements. browsers also accept :after, introduced in css2. examples simple usage let's create two classes: one for boring paragraphs and one for exciting ones. we can use these classes to ...
...olor: black; border-style: dotted; } result tooltips this example uses ::after, in conjunction with the attr() css expression and a data-descr custom data attribute, to create tooltips. no javascript is required! we can also support keyboard users with this technique, by adding a tabindex of 0 to make each span keyboard focusable, and using a css :focus selector. this shows how flexible ::before and ::after can be, though for the most accessible experience a semantic disclosure widget created in some other way (such as with details and summary elements) is likely to be more appropriate. html <p>here we have some <span tabindex="0" data-descr="collection of words and punctuation">text</span> with a few <span tabindex="0" data-descr="small popups that appear when hovering">tooltips</...
:not() - CSS: Cascading Style Sheets
Web › CSS › :not
the :not() css pseudo-class represents elements that do not match a list of selectors. since it prevents specific items from being selected, it is known as the negation pseudo-class. /* selects any element that is not a paragraph */ :not(p) { color: blue; } the :not() pseudo-class has a number of quirks, tricks, and unexpected results that you should be aware of before using it. syntax the :not() pseudo-class requires a comma-separated list of one or more selectors as its argument. the list must not contain another negation selector or a pseudo-element. the ability to list more than one selector is experimental and not yet widely supported. :not( <complex-selector-list> )where <complex-selector-list> = <complex-selector>#where <complex-selector> = <compound-selector> [ <combinator>? <...
...atcher> = [ '~' | | | '^' | '$' | '*' ]? '='<attr-modifier> = i | s description there are several unusual effects and outcomes when using :not() that you should keep in mind when using it: the :not pseudo-class may not be nested, which means that :not(:not(...)) is invalid. since pseudo-elements are not simple selectors, they are not valid arguments to :not(); thus, selectors like :not(p::before) will not work. useless selectors can be written using this pseudo-class. for example, :not(*) matches any element which is not an element, which is obviously nonsense, so the accompanying rule will never be applied. this pseudo-class can increase the specificity of a rule. for example, #foo:not(#bar) will match the same element as the simpler #foo, but has a higher specificity. :not(.foo) wil...
:target - CSS: Cascading Style Sheets
Web › CSS › :target
the target doesn't exist.</a></li> </ol> <h3>my fun article</h3> <p id="p1">you can target <i>this paragraph</i> using a url fragment. click on the link above to try out!</p> <p id="p2">this is <i>another paragraph</i>, also accessible from the links above. isn't that delightful?</p> css p:target { background-color: gold; } /* add a pseudo-element inside the target element */ p:target::before { font: 70% sans-serif; content: "►"; color: limegreen; margin-right: .25em; } /* style italic elements within the target element */ p:target i { color: red; } result pure-css lightbox you can use the :target pseudo-class to create a lightbox without using any javascript. this technique relies on the ability of anchor links to point to elements that are initially hidden on the p...
... living standard defines html-specific semantics. selectors level 4the definition of ...
Using CSS animations - CSS: Cascading Style Sheets
ence. animation-iteration-count configures the number of times the animation should repeat; you can specify infinite to repeat the animation indefinitely. animation-direction configures whether or not the animation should alternate direction on each run through the sequence or reset to the start point and repeat itself. animation-fill-mode configures what values are applied by the animation before and after it is executing. animation-play-state lets you pause and resume the animation sequence. defining the animation sequence using keyframes once you’ve configured the animation’s timing, you need to define the appearance of the animation. this is done by establishing two or more keyframes using the @keyframes at-rule. each keyframe describes how the animated element should render a...
... element.classname = "slidein"; this is pretty standard code; you can get details on how it works in the documentation for eventtarget.addeventlistener(). the last thing this code does is set the class on the element we'll be animating to “slidein”; we do this to start the animation. why? because the animationstart event fires as soon as the animation starts, and in our case, that happens before our code runs. so we’ll start the animation ourselves by setting the class of the element to the style that gets animated after the fact. receiving the events the events get delivered to the listener() function, which is shown below. function listener(event) { var l = document.createelement("li"); switch(event.type) { case "animationstart": l.innerhtml = "started: elapsed time ...
Border-radius generator - CSS: Cascading Style Sheets
span_5 { width: 40.7%; } .span_4 { width: 32.24%; } .span_3 { width: 23.78%; } .span_2 { width: 15.32%; } .span_1 { width: 6.86%; } /* sections * ========================================================================== */ .section { clear: both; padding: 0px; margin: 0px; } /* grouping * ========================================================================== */ .group: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 */ ...
...padding: 0; border-radius: 3px; position: absolute; overflow: hidden; } #unit-selection select { width: 50px; height: 20px; marign: 0; padding: 0 0 0 10px; background: #555; border: 1px solid #555; border: none; color: #fff; float: left; } #unit-selection select option { background: #fff; color: #333; } #unit-selection select:hover { cursor: pointer; } #unit-selection .dropdown:before { content: ""; width: 18px; height: 20px; display: block; background-color: #555; background-image: url("https://mdn.mozillademos.org/files/5675/dropdown.png"); background-position: center center; background-repeat: no-repeat; top: 0px; right: 0px; position: absolute; z-index: 1; pointer-events: none; } #unit-selection .unit-top-left { top: 0; left: 0; display: none; } #unit-sel...
Handling content breaks in multicol - CSS: Cascading Style Sheets
for example, we would generally prefer that the figcaption of an image not be separated into a new column away from the image it refers to and ending a column with a heading looks strange. the fragmentation properties give us ways to exercise some control over this. there are various 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. this property takes values of: auto avoid avoid-page avoid-column avoid-region in the example below, we have applied break-inside to the figure element to prevent the caption from becoming separated from the image. ...
...ter boxes, which would include our heading example above. breaks between lines. breaks inside boxes to control breaks inside boxes use the break-inside property. this property takes values of: auto avoid avoid-page avoid-column avoid-region in the example below, we have applied break-inside to the figure element to prevent the caption from becoming separated from the image. breaks before and after boxes the break-before and break-after properties are used to control breaks before and after elements. they take the following values when in a multicol context: auto avoid avoid-column column in this next example, we are forcing a column break before an h2 element. breaks between lines the orphans and widows properties are also useful. the orphans property controls the nu...
Auto-placement in CSS Grid Layout - CSS: Cascading Style Sheets
at they are entered in the document source. items with placement properties the first thing grid will do is place any items that have a position. in the example below i have 12 grid items. item 2 and item 5 have been placed using line based placement on the grid. you can see how those items are placed and the other items then auto-place in the spaces. the auto-placed items will place themselves before the placed items in dom order, they don’t start after the position of a placed item that comes before them. * {box-sizing: border-box;} .wrapper { border: 2px solid #f76707; border-radius: 5px; background-color: #fff4e6; } .wrapper > div { border: 2px solid #ffa94d; border-radius: 5px; background-color: #ffd8a8; padding: 1em; color: #d9480f; } <div class=...
...like to create a layout that doesn’t have gaps in it. to do this, add the property grid-auto-flow with a value of dense to the container. this is the same property you use to change the flow order to column, so if you were working in columns you would add both values grid-auto-flow: column dense. having done this, grid will now backfill the gaps, as it moves through the grid it leaves gaps as before, but then if it finds an item that will fit in a previous gap it will pick it up and take it out of dom order to place it in the gap. as with any other reordering in grid this does not change the logical order. tab order for example, will still follow the document order. we will take a look at the potential accessibility issues of grid layout in a later guide, but you should take care when creati...
Basic Concepts of grid layout - CSS: Cascading Style Sheets
: 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: #ffd8a8; padding: 1em; color: #d9480f; } all the direct children are now grid items. in a web browser, you won’t see any difference to how these items are displayed before turning them into a grid, as grid has created a single column grid for the items. at this point, you may find it useful to work with the grid inspector, available as part of firefox's developer tools. if you view this example in firefox and inspect the grid, you will see a small icon next to the value grid. click this and then the grid on this element will be overlaid in the browser window. as...
...in terms of line-based positioning, the gap acts like a fat line. nesting grids a grid item can become a grid container. in the following example, i have the three-column grid that i created earlier, with our two positioned items. in this ...
Layout using named grid lines - CSS: Cascading Style Sheets
grid a unique name then you will need to write out the track definition long-hand rather than using the repeat syntax, as you need to add the name in square brackets while defining the tracks. if you do use the repeat syntax you will end up with multiple lines that have the same name, however this can be very useful too. in this next example i am creating a grid with twelve equal width columns. before defining the 1fr size of the column track i am also defining a line name of [col-start]. this means that we will end up with a grid that has 12 column lines all named col-start before a 1fr width column. * {box-sizing: border-box;} .wrapper { border: 2px solid #f76707; border-radius: 5px; background-color: #fff4e6; } .wrapper > div { border: 2px solid #ffa94d; border-radius: 5px; ...
...-column: col-start / span 3; grid-row: 2; } .content { grid-column: col-start 4 / span 6; grid-row: 2; } .side2 { grid-column: col-start 10 / span 3; grid-row: 2; } once again, the grid highlighter is helpful to show us how the grid we have placed our items on works. that’s all i need. i don’t need to do any calculations, grid automatically removed my 10 pixel gutter track before assigning the space to the 1fr column tracks. as you start to build out your own layouts, you will find that the syntax becomes more familiar and you choose the ways that work best for you and the type of projects you like to build. try building some common patterns with these various methods, and you will soon find your most productive way to work. then, in the next guide we will look at how gri...
Relationship of grid layout to other layout methods - CSS: Cascading Style Sheets
; border-radius: 5px; background-color: #ffd8a8; padding: 1em; color: #d9480f; } <div class="wrapper"> <div>one</div> <div>two</div> <div>three</div> </div> .wrapper { display: grid; grid-template-columns: repeat(auto-fill, 200px); } a flexible number of tracks this isn’t quite the same as flexbox. in the flexbox example, the items are larger than the 200 pixel basis before wrapping. we can achieve the same in grid by combining auto-fit and the minmax() function. in this next example, i create auto filled tracks with minmax. i want my tracks to be a minimum of 200 pixels, so i set the maximum to be 1fr. once the browser has worked out how many times 200 pixels will fit into the container–also taking account of grid gaps–it will treat the 1fr maximum as an instru...
... the wrapper above, positioning context is from the viewport, as shown in this image. once again the item no longer participates in the grid layout in terms of sizing or when other items are auto-placed. with a grid area as the parent if the absolutely positioned item is nested inside a grid area then you can create a positioning context on that area. in the below example we have our grid as before but this time i have nested an item inside .box3 of the grid. i have given .box3 position relative and then positioned the sub-item with the offset properties. in this case, the positioning context is the grid area. * {box-sizing: border-box;} .wrapper { border: 2px solid #f76707; border-radius: 5px; background-color: #fff4e6; } .wrapper > div { border: 2px solid #ffa94d; border-ra...
Basic Shapes - CSS: Cascading Style Sheets
css shapes can be defined using the <basic-shape> type, and in this guide i’ll explain how each of the different values accepted by this type work. they range from simple circles to complex polygons. before looking at the shapes, it is worth understanding two pieces of information that go together to make these shapes possible: the <basic-shape> type the reference box the <basic-shape> type the <basic-shape> type is used as the value for all of our basic shapes. this type uses functional notation: the type of shape is followed by brackets, inside of which are additional values used to describe the shape. the arguments which are accepted vary depending on the shape that you are creating. we will cover these in the examples below. the reference box understanding the reference box use...
... round 10px); } in the example below we have an inset() shape used to pull content over the floated element. change the offset values to see how the shape changes. you can also add the box value that you wish to use as a reference box. in the example below change the reference box from margin-box to border-box, padding-box or content-box to see how the reference box used as the starting point before offsets are calculated changes. circle() the circle() value for shape-outside can accept two possible arguments. the first is the shape-radius. both circle() and ellipse() values for shape-outside are specified as accepting this argument of <shape-radius>. this argument can be a length or percentage but can also be one of the keywords closest-side or farthest-side. the keyword closest-side ...
Pseudo-elements - CSS: Cascading Style Sheets
mple selectors in the statement. note: as a rule, double colons (::) should be used instead of a single colon (:). this distinguishes pseudo-classes from pseudo-elements. however, since this distinction was not present in older versions of the w3c spec, most browsers support both syntaxes for the original pseudo-elements. ...
...ctors in the statement. note: as a rule, double colons (::) should be used instead of a single colon (:). this distinguishes pseudo-classes from pseudo-elements. however, since this distinction was not present in older versions of the w3c spec, most browsers support both syntaxes for the original pseudo-elements. ...
Visual formatting model - CSS: Cascading Style Sheets
flex item, however, it cannot be targeted and styled like a regular box because there is no element to target. the same thing happens when you have text runs interspersed with block elements. in the next example i have a string inside a <div>; in the middle of my string is a <p> element containing part of the text. the string is split into three boxes in the box tree. the part of the string before the paragraph element is wrapped in an anonymous box, then we have the <p>, which generates a box, and then another anonymous box. something to consider about these anonymous boxes is that they inherit styles from their direct parent, but you cannot change how they look by targeting the anonymous box. in my examples, i am using a direct child selector to target the children of the container. thi...
...mples, i am using a direct child selector to target the children of the container. this does not change the anonymous boxes, as they are not a child of the parent block. inline anonymous boxes are created when a string is split by an inline element, for example, a sentence that includes a section wrapped with <em></em>. this splits the sentence into three inline boxes — an anonymous inline box before the emphasized section, the section wrapped in the <em> element, then a final anonymous inline box. as with the anonymous block boxes, these anonymous inline boxes cannot be styled independently in the way the <em> can; they just inherit the styles of their container. other formatting contexts also create anonymous boxes. grid layout behaves in the same way as the flexbox example above, turning ...
animation-fill-mode - 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. it is often convenient to use the shorthand property animation to set all animation properties at once. ...
...ng 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 definition initial valuenoneapplies toall elements, ::before and ::after pseudo-elementsinheritednocomputed valueas specifiedanimation typediscrete formal syntax <single-animation-fill-mode>#where <single-animation-fill-mode> = none | forwards | backwards | both examples you can see the effect of animation-fill-mode in the following example. it demonstrates how, for an animation that runs for an infinite time, you can cause it to remain in its final st...
animation-iteration-count - CSS: Cascading Style Sheets
if multiple values are specified, each time the animation is played the next value in the list is used, cycling back to the first value after the last one is 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. it is often convenient to use the shorthand property animation to set all animation properties at once. ...
...ill play half of the animation cycle. negative values are invalid. note: when you specify multiple 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 definition initial value1applies toall elements, ::before and ::after pseudo-elementsinheritednocomputed valueas specifiedanimation typediscrete formal syntax <single-animation-iteration-count>#where <single-animation-iteration-count> = infinite | <number> examples see css animations for examples. specifications specification status comment css animationsthe definition of 'animation-iteration-count' in that specificatio...
animation - CSS: Cascading Style Sheets
Web › CSS › animation
ues <single-animation-iteration-count> the number of times the animation is played. the value must be one of those available in animation-iteration-count. <single-animation-direction> the direction in which the animation is played. the value must be one of those available in animation-direction. <single-animation-fill-mode> determines how styles should be applied to the animation's target before and after its execution. the value must be one of those available in animation-fill-mode. <single-animation-play-state> determines whether the animation is playing or not. the value must be one of those available in animation-play-state. accessibility concerns blinking and flashing animation can be problematic for people with cognitive concerns such as attention deficit hyperactivity disorde...
... guideline 2.2 explanations understanding success criterion 2.2.2 | w3c understanding wcag 2.0 formal definition initial valueas each of the properties of the shorthand:animation-name: noneanimation-duration: 0sanimation-timing-function: easeanimation-delay: 0sanimation-iteration-count: 1animation-direction: normalanimation-fill-mode: noneanimation-play-state: runningapplies toall elements, ::before and ::after pseudo-elementsinheritednocomputed valueas each of the properties of the shorthand:animation-name: as specifiedanimation-duration: as specifiedanimation-timing-function: as specifiedanimation-delay: as specifiedanimation-direction: as specifiedanimation-iteration-count: as specifiedanimation-fill-mode: as specifiedanimation-play-state: as specifiedanimation typediscrete formal syntax...
break-after - CSS: Cascading Style Sheets
to determine if a break must be done, the following rules are applied: if any of the three concerned values is a forced break value (always, left, right, page, column, or region), it has precedence. if more than one of them are such a break, the one of the element that appears the latest in the flow is taken (i.e...
... next element, and the break-inside value of the containing element. to determine if a break must be done, the following rules are applied: if any of the three concerned values is a forced break value (always, left, right, page, column, or region), it has precedence. if more than one of them are such a break, the one of the element that appears the latest in the flow is taken (i.e., the break-before value has precedence over the break-after value, which itself has precedence over the break-inside value). if any of the three concerned values is an avoid break value (avoid, avoid-page, avoid-region, or avoid-column), no such break will be applied at that point. once forced breaks have been applied, soft breaks may be added if needed, but not on element boundaries that resolve in a correspon...
break-inside - CSS: Cascading Style Sheets
ignored. /* keyword values */ break-inside: auto; break-inside: avoid; break-inside: avoid-page; break-inside: avoid-column; break-inside: avoid-region; /* global values */ break-inside: inherit; break-inside: initial; break-inside: unset; each possible break point (in other words, each element boundary) is affected by three properties: the break-after value of the previous element, the break-before value of the next element, and the break-inside value of the containing element. to determine if a break must be done, the following rules are applied: if any of the three concerned values is a forced break value (always, left, right, page, column, or region), it has precedence. if more than one of them are such a break, the value of the element that appears the latest in the flow is used. th...
...next element, and the break-inside value of the containing element. to determine if a break must be done, the following rules are applied: if any of the three concerned values is a forced break value (always, left, right, page, column, or region), it has precedence. if more than one of them are such a break, the value of the element that appears the latest in the flow is used. thus, the break-before value has precedence over the break-after value, which in turn has precedence over the break-inside value. if any of the three concerned values is an avoid break value (avoid, avoid-page, avoid-region, or avoid-column), no such break will be applied at that point. once forced breaks have been applied, soft breaks may be added if needed, but not on element boundaries that resolve in a correspon...
grid-column - CSS: Cascading Style Sheets
t, please clone https://github.com/mdn/interactive-examples and send us a pull request. constituent properties this property is a shorthand for the following css properties: grid-column-end grid-column-start syntax this property is specified as one or two <grid-line> values. if two <grid-line> values are given they are separated by "/". the grid-column-start longhand is set to the value before the slash, and the grid-column-end longhand is set to the value after the slash. each <grid-line> value can be specified as: either the auto keyword or a <custom-ident> value or an <integer> value or both <custom-ident> and <integer>, separated by a space or the keyword span together with either a <custom-ident> or an <integer> or both. values auto is a keyword indicating that the p...
...m-ident> if there is a named line with the name '<custom-ident>-start'/'<custom-ident>-end', it contributes the first such line to the grid item’s placement. note: named grid areas automatically generate implicit named lines of this form, so specifying grid-column: foo; will choose the start/end edge of that named grid area (unless another line named foo-start/foo-end was explicitly specified before it). otherwise, this is treated as if the integer 1 had been specified along with the <custom-ident>. <integer> && <custom-ident>? contributes the nth grid line to the grid item’s placement. if a negative integer is given, it instead counts in reverse, starting from the end edge of the explicit grid. if a name is given as a <custom-ident>, only lines with that name are counted. if not en...
grid-row - CSS: Cascading Style Sheets
Web › CSS › grid-row
acement, 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. 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. constituent properties this property is a shorthand for the following css properties: grid-row-end grid-row-start syntax /* keyword values */ grid-row: auto; grid-row: auto / auto; /* <custom-ident> values */ grid-row: somegridarea; grid-row: somegridarea / someothergridarea; /* <integer> + <custom-ident> val...
...stom-ident> if there is a named line with the name '<custom-ident>-start'/'<custom-ident>-end', it contributes the first such line to the grid item’s placement. note: named grid areas automatically generate implicit named lines of this form, so specifying grid-row: foo; will choose the start/end edge of that named grid area (unless another line named foo-start/foo-end was explicitly specified before it). otherwise, this is treated as if the integer 1 had been specified along with the <custom-ident>. <integer> && <custom-ident>? contributes the nth grid line to the grid item’s placement. if a negative integer is given, it instead counts in reverse, starting from the end edge of the explicit grid. if a name is given as a <custom-ident>, only lines with that name are counted. if not en...
<image> - CSS: Cascading Style Sheets
Web › CSS › image
border image area cursor the browser-defined size matching the usual cursor size on the client's system mask-image ? shape-outside ? mask-border-source ? symbols for @counter-style at risk feature. if supported, the browser-defined size matching the usual cursor size on the client's system content for a pseudo-element (::after/::before) a 300px × 150px rectangle the concrete object size is calculated using the following algorithm: if the specified size defines both the width and the height, these values are used as the concrete object size. if the specified size defines only the width or only the height, the missing value is determined using the intrinsic ratio, if there is any, the intrinsic dimensions if the sp...
...ons specification status comment css images module level 4the definition of '<image>' in that specification. working draft adds element(), image(), image-set(), conic-gradient(), repeating-conic-gradient(), and image-resolution. css images module level 3the definition of '<image>' in that specification. candidate recommendation initial definition. before this, there was no explicitly defined <image> data type. images could only be defined using the url() functional notation. ...
list-style-type - CSS: Cascading Style Sheets
l -moz-hangul example example example hangul-consonant -moz-hangul-consonant example example example urdu -moz-urdu example accessibility concerns the voiceover screen reader has an issue where unordered lists with a list-style-type value of none applied to them will not be announced as a list. ...
...ver screen reader has an issue where unordered lists with a list-style-type value of none applied to them will not be announced as a list. to address this, add a zero-width space as pseudo content before each list item to ensure the list is announced properly. this ensures the design is unaffected by the bug fix and that list items are not improperly described. ...
list-style - CSS: Cascading Style Sheets
lues list-style-type see list-style-type. list-style-image see list-style-image. list-style-position see list-style-position. none no list style is used. accessibility concerns safari has an issue whereby unordered lists with a list-style value of none applied to them will not be recognized as a list in the accessibility tree. ...
...issue whereby unordered lists with a list-style value of none applied to them will not be recognized as a list in the accessibility tree. to address this, add a zero-width space as pseudo-content before each list item to ensure the list is recognized properly. this ensures the design is unaffected by the bug fix and that list items are not improperly described. ...
ruby-position - CSS: Cascading Style Sheets
f having display: inline on the ruby), and above (synonym of the modern over).opera no support nosafari no support nonotes no support nonotes notes safari implements a non-standard, prefixed, version of ruby-position, -webkit-ruby-position: it has two properties: before and after (both equivalent, for ltr and rtl scripts to the standard over value used with ruby-align: start).webview android no support nochrome android no support nofirefox android full support 38opera android no support ...
...droid full support 38opera android no support nosafari ios no support nonotes no support nonotes notes safari implements a non-standard, prefixed, version of ruby-position, -webkit-ruby-position: it has two properties: before and after (both equivalent, for ltr and rtl scripts to the standard over value used with ruby-align: start).samsung internet android no support nointer-character experimentalchrome no support noedge no support nofirefox no support ...
transition-delay - CSS: Cascading Style Sheets
the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. the delay may be zero, positive, or negative: a value of 0s (or 0ms) will begin the transition effect immediately. a positive value will delay the start of the transition effect for the given length of time. a negative value will begin the transition effect immediately, and partway through the effect. ...
...s declaration remains valid. syntax /* <time> values */ transition-delay: 3s; transition-delay: 2s, 4ms; /* global values */ transition-delay: inherit; transition-delay: initial; transition-delay: unset; values <time> denotes the amount of time to wait between a property's value changing and the start of the transition effect. ...
Adding captions and subtitles to HTML5 video - Developer guides
er and show how to add captions and subtitles to it, using the webvtt format and the <track> element. captioned video example in this article, we will refer to the video player with captions example. this example uses an excerpt from the sintel open movie, created by the blender foundation. note: you can find the source on github, and also view the example live. html5 and video captions before diving into how to add captions to the video player, there are a number of things that we will first mention, which you should be aware of before we start. captions versus subtitles captions and subtitles are not the same thing: they have significantly different audiences, and convey different information, and it is recommended that you read up on the differences if you are not sure what they a...
...one and set its mode to hidden. note: the webvtt api gives us access to all the text tracks that are defined for an html5 video using the <track> element. building a caption menu our aim is to use the subtitles button we added earlier to display a menu that allows users to choose which language they want the subtitles displayed in, or to turn them off entirely. we have added the button, but before we make it do anything, we need to build the menu that goes with it. this menu is built dynamically, so that languages can be added or removed later by simply editing the <track> elements within the video's markup. all we need to do is to go through the video's texttracks, reading their properties and building the menu up from there: var subtitlesmenu; if (video.texttracks) { var df = docume...
Audio and Video Delivery - Developer guides
lement.load(); by removing the media element's src attribute and invoking the load() method, you release the resources associated with the video, which stops the network download. you must call load() after removing the attribute, because just removing the src attribute does not invoke the load algorithm. if the <video> element also has <source> element descendants, those should also be removed before calling load(). note that just setting the src attribute to an empty string will actually cause the browser to treat it as though you're setting a video source to a relative path. this causes the browser to attempt another download to something that is unlikely to be a valid video. seeking through media media elements provide support for moving the current playback position to specific points ...
...the sources are tried in the order in which they appear, and once one loads successfully, the remaining sources aren't tried at all. checking whether the browser supports the supplied formats use the following verified sources within your audio and video elements to check support. audio mp3 (type="audio/mpeg"): http://jplayer.org/audio/mp3/miaow-01-tempered-song.m...
HTML5 Parser - Developer guides
Web › Guide › HTML › HTML5 › HTML5 Parser
y they are tokenized in html, so you can omit quotes in the same situations where you can omit quotes in html (i.e. when the attribute value is not the empty string and does not contain whitespace, ", ', `, <, =, or >). warning: the two above features do not combine well due to the reuse of legacy-compatible html tokenization. if you omit quotes on the last attribute value, you must have a space before the closing slash. <circle fill=green /> is ok but <circle fill=red/> is not. attributes starting with xmlns have absolutely no effect on what namespace elements or attributes end up in, so you don’t need to use attributes starting with xmlns. attributes in the xlink namespace must use the prefix xlink (e.g. xlink:href). element names must not have prefixes or colons in them. the content of...
...e these tasks in parallel. to best take advantage of speculative parsing, and help your pages to load as quickly as possible, ensure that when you call document.write(), you write a balanced sub-tree within that chunk of script. a balanced sub-tree is html code in which any elements that are opened are also closed, so that after the script, the elements left open are the same ones that were open before the script. the open and closing tags do not need to be written by 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>. (there are also some element whose ...
Date and time formats used in HTML - HTML: Hypertext Markup Language
that let the user choose or specify a date, time, or both, as well as the <ins> and <del> elements, whose datetime attribute specifies the date or date and time at which the insertion or deletion of content occurred. for <input>, the values of type that return a value which contains a string representing a date and/or time are: date datetime datetime-local month time week examples before getting into the intricacies of how date and time strings are written and parsed in html, here are some examples that should give you a good idea what the more commonly-used date and time string formats look like. example html date and time strings string date and/or time 2005-06-07 june 7, 2005 [details] 08:45 8:45 am [details] 08:45:25 ...
...html uses a variation of the iso 8601 standard for its date and time strings. it's worth reviewing the descriptions of the formats you're using in order to ensure that your strings are in fact compatible with html, as the html sp...
<del>: The Deleted Text element - HTML: Hypertext Markup Language
Web › HTML › Element › del
l date and time strings. examples <p><del>this text has been deleted</del>, here is the rest of the paragraph.</p> <del><p>this paragraph has 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. ...
...el>this text has been deleted</del>, here is the rest of the paragraph.</p> <del><p>this paragraph has been deleted.</p></del> result accessibility concerns the presence of the del element is not announced by most screen reading technology in its default configuration. it can be made to be announced by using the css content property, along with the ::before and ::after pseudo-elements. del::before, del::after { clip-path: inset(100%); clip: rect(1px, 1px, 1px, 1px); height: 1px; overflow: hidden; position: absolute; white-space: nowrap; width: 1px; } del::before { content: " [deletion start] "; } del::after { content: " [deletion end] "; } some people who use screen readers deliberately disable announcing content that creates extra verbosity. because of this, it is im...
<hgroup> - HTML: Hypertext Markup Language
Web › HTML › Element › hgroup
, some choice must be made in the design of the rendering tool about how to render <hgroup> headings in such a way as to convey their multi-level nature. ...
...ender <hgroup> headings in such a way as to convey their multi-level nature. ...
<input type="date"> - HTML: Hypertext Markup Language
Web › HTML › Element › input › date
urs afterward, the element fails constraint validation. if the value of the max attribute isn't a possible date string in the format yyyy-mm-dd, then the element has no maximum date value. if both the max and min attributes are set, this value must be a date string later than or equal to the one in the min attribute. min the earliest date to accept. if the value entered into the element occurs beforehand, the element fails constraint validation. if the value 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 mus...
...f(dayselect.value === "") { dayselect.value = previousday - 1; } if(dayselect.value === "") { dayselect.value = previousday - 2; } if(dayselect.value === "") { dayselect.value = previousday - 3; } } } function populateyears() { // get this year as a number var date = new date(); var year = date.getfullyear(); // make this year, and the 100 years before it available in the year <select> for(var i = 0; i <= 100; i++) { var option = document.createelement('option'); option.textcontent = year-i; yearselect.appendchild(option); } } // when the month or year <select> values are changed, rerun populatedays() // in case the change affected the number of available days yearselect.onchange = function() { populatedays(monthselect.value)...
<input type="password"> - HTML: Hypertext Markup Language
Web › HTML › Element › input › password
e user agent and os. the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. specifics of how the entry process works may vary from browser to browser; mobile devices, for example, often display the typed character for a moment before obscuring it, to allow the user to be sure they pressed the key they meant to press; this is helpful given the small size of keys and the ease with which the wrong one can be pressed, especially on virtual keyboards. note: any forms involving sensitive information like passwords (e.g. login forms) should be served over https; many browsers now implement mechanisms to warn against insecure login...
...in a variety of ways, depending on the password manager in use. it may simply fill in a new suggested password, or it might show the user an interface for creating one. <label for="userpassword">password:</label> <input id="userpassword" type="password" autocomplete="current-password"> making the password mandatory to tell the user's browser that the password field must have a valid value before the form can be submitted, simply specify the boolean required attribute. <label for="userpassword">password: </label> <input id="userpassword" type="password" required> <input type="submit" value="submit"> specifying an input mode if your recommended (or required) password syntax rules would benefit from an alternate text entry interface than the standard keyboard, you can use the inputmode...
<input type="submit"> - HTML: Hypertext Markup Language
Web › HTML › Element › input › submit
action 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, means the form's fields will not be subjected to constraint validation before submitting the data to the server formtarget the browsing context into which to load the response returned by the server after submitting the form formaction a string indicating the url to which to submit the data. this takes precedence over the action attribute on the <form> element that owns the <input>. this attribute is also available on <input type="image"> and <button> ...
... method supports complex data and file attachments. dialog this method is used to indicate that the button simply closes the dialog with which the input is associated, and does not transmit the form data at all. this attribute is also available on <input type="image"> and <button> elements. formnovalidate a boolean attribute which, if present, specifies that the form should not be validated before submission to the server. this overrides the value of the novalidate attribute on the element's owning form. this attribute is also available on <input type="image"> and <button> elements. formtarget a string which specifies a name or keyword that indicates where to display the response received after submitting the form. the string must be the name of a browsing context (that is, a tab, windo...
<input type="text"> - HTML: Hypertext Markup Language
Web › HTML › Element › input › text
mail, or search term, you've got better options available). basic example <form> <div> <label for="uname">choose a username: </label> <input type="text" id="uname" name="name"> </div> <div> <button>submit</button> </div> </form> this renders like so: when submitted, the data name/value pair sent to the server will be uname=chris (if "chris" was entered as the input value before submission). you must remember to include name attribute on the <input> element, otherwise the text field's value won't be included with the submitted data. setting placeholders you can provide a useful placeholder inside your text input that can provide a hint as to what to enter by including using the placeholder attribute. look at the following example: <form> <div> <label for="uname"...
...bsolute; content: '✓'; padding-left: 5px; } the technique also requires a <span> element to be placed after the form element, which acts as a holder for the icons. this was necessary because some input types on some browsers don't display icons placed directly after them very well. ...
<input type="time"> - HTML: Hypertext Markup Language
Web › HTML › Element › input › time
onds (see using the step attribute), the format is always hh:mm:ss. you can learn more about the format of the time value used by this input type in time strings in date and time formats used in html. in this example, you can see the time input's value by entering a time and seeing how it changes afterward. first, a look at the html. this is simple enough, with the label and input as we've seen before, but with the addition of a <p> element with a <span> to display the value of the time input: <form> <label for="starttime">start time: </label> <input type="time" id="starttime"> <p> value of the <code>time</code> input: <code> "<span id="value">n/a</span>"</code>. </p> </form> the javascript code adds code to the time input to watch for the input event, which is trigge...
...put element change. when this happens, the contents of the <span> are replaced with the new value of the input element. var starttime = document.getelementbyid("starttime"); var valuespan = document.getelementbyid("value"); starttime.addeventlistener("input", function() { valuespan.innertext = starttime.value; }, 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). additional attributes in addition to the attributes common to all <input> elements, time inputs offer the following attributes: attribute description list the id of the <datali...
<input type="url"> - HTML: Hypertext Markup Language
Web › HTML › Element › input › url
elements of type url are used to let the user enter and edit a url. the source for this interactive example is stored in a github repository. if 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 input value is automatically validated to ensure that it's either empty or a properly-formatted url before the form can be submitted. the :valid and :invalid css pseudo-classes are automatically applied as appropriate to visually denote whether the current value of the field is a valid url or not. on browsers that don't support inputs of type url, a url input falls back to being a standard text input. value a domstring representing a url, or empty events change and input ...
...ion browsers that support the url input type automatically provide validation to ensure that only text that matches the standard format for urls is entered into the input box. the syntax of a url is fairly intricate. it's defined by whatwg's url living standard and is described for newcomers in our article what is a url? making a url required as mentioned earlier, to make a url entry required before the form can be submitted (you can't leave the field blank), you just need to include the required attribute on the input. <form> <input id="myurl" name="myurl" type="url" required> <button>submit</button> </form> try submitting the above form with no value entered to see what happens. pattern validation if you need the entered url to be restricted further than just "any string that l...
<ins> - HTML: Hypertext Markup Language
Web › HTML › Element › ins
format of the string if it includes both date and time is covered in format of a valid local date and time string. examples <ins>this text has been inserted</ins> result accessibility concerns the presence of the <ins> element is not announced by most screen reading technology in its default configuration. ...
...date and time is covered in format of a valid local date and time string. examples <ins>this text has been inserted</ins> result accessibility concerns the presence of the <ins> element is not announced by most screen reading technology in its default configuration. it can be made to be announced by using the css content property, along with the ::before and ::after pseudo-elements. ins::before, ins::after { clip-path: inset(100%); clip: rect(1px, 1px, 1px, 1px); height: 1px; overflow: hidden; position: absolute; white-space: nowrap; width: 1px; } ins::before { content: " [insertion start] "; } ins::after { content: " [insertion end] "; } some people who use screen readers deliberately disable announcing content that creates extra verbosity. because of this, it is ...
<listing> - HTML: Hypertext Markup Language
Web › HTML › Element › listing
eroperasafariandroid webviewchrome for androidfirefox for androidopera for androidsafari on iossamsung internetlisting deprecatedchrome no support noedge no support nofirefox no support nonotes no support nonotes notes before firefox 4, this element implemented the htmlspanelement interface instead of the standard htmlelement interface.ie no support noopera no support nosafari no support nowebview android no support nochrome android ...
...pport nosafari no support nowebview android no support nochrome android no support nofirefox android no support nonotes no support nonotes notes before firefox 4, this element implemented the htmlspanelement interface instead of the standard htmlelement interface.opera android no support nosafari ios no support nosamsung internet android no support nolegend no support ...
<mark>: The Mark Text element - HTML: Hypertext Markup Language
Web › HTML › Element › mark
to help distinguish the use of <mark> for search results from other potential usage, this example applies the custom class "match" to each match. 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. ...
...search results from other potential usage, this example applies the custom class "match" to each match. the results look like this: accessibility concerns the presence of the mark element is not announced by most screen reading technology in its default configuration. it can be made to be announced by using the css content property, along with the ::before and ::after pseudo-elements. mark::before, mark::after { clip-path: inset(100%); clip: rect(1px, 1px, 1px, 1px); height: 1px; overflow: hidden; position: absolute; white-space: nowrap; width: 1px; } mark::before { content: " [highlight start] "; } mark::after { content: " [highlight end] "; } some people who use screen readers deliberately disable announcing content that creates extra verbosity. because of this, it ...
<p>: The Paragraph element - HTML: Hypertext Markup Language
Web › HTML › Element › p
<p> element represents a paragraph. paragraphs are usually represented in visual media as blocks of text separated from adjacent blocks by blank lines and/or first-line indentation, but html paragraphs can be any structural grouping of related content, such as images or form fields. paragraphs are block-level elements, and notably will automatically close if another block-level element is parsed before the closing </p> tag. see “tag omission” below. the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. content categories flow content, palpable content. permitted content phrasing content. ...
...ing, paragraphs were separated with a special character: ¶, the <i>pilcrow</i>. ...
<s> - HTML: Hypertext Markup Language
Web › HTML › Element › s
anelement interface for this element. examples <s>today's special: salmon</s> sold out<br> <span style="text-decoration:line-through;">today'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. ...
...xamples <s>today's special: salmon</s> sold out<br> <span style="text-decoration:line-through;">today's special: salmon</span> sold out accessibility concerns the presence of the s element is not announced by most screen reading technology in its default configuration. it can be made to be announced by using the css content property, along with the ::before and ::after pseudo-elements. s::before, s::after { clip-path: inset(100%); clip: rect(1px, 1px, 1px, 1px); height: 1px; overflow: hidden; position: absolute; white-space: nowrap; width: 1px; } s::before { content: " [start of stricken text] "; } s::after { content: " [end of stricken text] "; } some people who use screen readers deliberately disable announcing content that creates extra verbosity. because of this...
<source>: The Media or Image Source element - HTML: Hypertext Markup Language
Web › HTML › Element › source
te to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. content categories none. permitted content none, it is an empty element. tag omission it must have a start tag, but must not have an end tag. permitted parents a media element—<audio> or <video>—and it must be placed before any flow content or <track> element. a <picture> element, and it must be placed before the <img> element. implicit aria role no corresponding role permitted aria roles no role permitted dom interface htmlsourceelement attributes this element includes the global attributes. media media query of the resource's intended media; this should be us...
...element includes the global attributes. media media query of the resource's intended media; this should be used only in a <picture> element. sizes is a list of source sizes that describes the final rendered width of the image represented by the source. each source size consists of a comma-separated list of media condition-length pairs. this information is used by the browser to determine, before laying the page out, which image defined in srcset to use. please note that sizes will have its effect only if width dimension descriptors are provided with srcset instead of pixel ratio values (200w instead of 2x for example). the sizes attribute has an effect only when the <source> element is the direct child of a <picture> element. src required for <audio> and <video>, address of the med...
<video>: The Video Embed element - HTML: Hypertext Markup Language
Web › HTML › Element › video
me sets the current playback position to the given time and seeks the media to that position if the media is currently loaded. if the media is being streamed, it's possible that the user agent may not be able to obtain some parts of the resource if that data has expired from the media buffer. other media may have a media timeline that doesn't start at 0 seconds, so setting currenttime to a time before that would fail. the getstartdate() method can be used to determine the beginning point of the media timeline's reference frame. disablepictureinpicture prevents the browser from suggesting a picture-in-picture context menu or to request picture-in-picture automatically in some cases. disableremoteplayback a boolean attribute used to disable the capability of remote playback in devices ...
...oster a url for an image to be shown while the video is downloading. if this attribute isn't specified, nothing is displayed until the first frame is available, then the first frame is shown as the poster frame. preload this enumerated attribute is intended to provide a hint to the browser about what the author thinks will lead to the best user experience with regards to what content is loaded before the video is played. it may have one of the following values: none: indicates that the video should not be preloaded. metadata: indicates that only video metadata (e.g. length) is fetched. auto: indicates that the whole video file can be downloaded, even if the user is not expected to use it. empty string: synonym of the auto value. the default value is different for each browser. t...
HTML documentation index - HTML: Hypertext Markup Language
Web › HTML › Index
. 137 <input type="tel"> element, form inputs, forms, html, html forms, html input, input, input element, input type, phone numbers, reference, telephone numbers, tel <input> elements of type tel are used to let the user enter and edit a telephone number. unlike <input type="email"> and <input type="url"> , the input value is not automatically validated to a particular format before the form can be submitted, because formats for telephone numbers vary so much around the world. 138 <input type="text"> form input, forms, html, html forms, input, input type, reference, text, text entry, text input <input> elements of type text create basic single-line text fields. 139 <input type="time"> element, forms, html, html input types, html forms, htm...
...earning new attributes. 235 preloading content with rel="preload" guide, html, javascript, link, media, performance, web performance, as, preload, rel the preload value of the <link> element's rel attribute lets you declare fetch requests in the html's <head>, specifying resources that your page will need very soon, which you want to start loading early in the page lifecycle, before browsers' main rendering machinery kicks in. 236 quirks mode and standards mode gecko, guide, html, needsupdate, web development, web standards, xhtml in the old days of the web, pages were typically written in two versions: one for netscape navigator, and one for microsoft internet explorer. when the web standards were made at w3c, browsers could not just start using them, a...
Inline elements - HTML: Hypertext Markup Language
changing element levels you can change the visual presentation of an element using the css display property. for example, by changing the value of display from "inline" to "block", you can ...
...ing and end of the block-level element's influence.</div> the css (not displayed in standard reading mode) is also used: body { margin: 0; padding: 4px; border: 1px solid #333; } .highlight { background-color:#ee3; } rendered using the same css as before, we get: see the difference? the <p> element totally changes the layout of the text, splitting it into three segments: the text before the <p>, then the <p>'s text, and finally the text following the <p>. changing element levels you can change the visual presentation of an element using the css display property. for example, by changing the value of display from "inline" to "block", you can tell the browser to render the inline element in a block box rather than an inline box, and vice versa. however, doing this will not chang...
Quirks Mode and Standards Mode - HTML: Hypertext Markup Language
owsers therefore introduced two modes to treat new standards compliant sites differently from old legacy sites. there are now three modes used by the layout engines in web browsers: quirks mode, almost standards mode, and full standards mode. in quirks mode, layout emulates nonstandard behavior in navigator 4 and internet explorer 5. this is essential in order to support websites that were built before the widespread adoption of web standards. in full standards mode, the behavior is (hopefully) the behavior described by the html and css specifications. in almost standards mode, there are only a very small number of quirks implemented. how do browsers determine which mode to use? for html documents, browsers use a doctype in the beginning of the document to decide whether to handle it in quirk...
...ecommended other variants, but all existing browsers today will use full standards mode for this doctype, even the dated internet explorer 6. there are no valid reasons to use a more complicated doctype. if you do use another doctype, you may risk choosing one which triggers almost standards mode or quirks mode. make sure you put the doctype right at the beginning of your html document. anything before the doctype, like a comment or an xml declaration will trigger quirks mode in internet explorer 9 and older. in html5, the only purpose of the doctype is to activate full standards mode. older versions of the html standard gave additional meaning to the doctype, but no browser has ever used the doctype for anything other than switching between quirks mode and standards mode. see also a detailed...
Evolution of HTTP - HTTP
1996, in order to solve these annoyances, an informational document describing the common practices has been published, rfc 1945. this is the definition of http/1.0 and it is notable that, in the narrow sense of the term, it isn't an official standard. http/1.1 – the standardized protocol in parallel to the somewhat chaotic use of the diverse implementations of http/1.0, and since 1995, well before the publication of http/1.0 document the next year, proper standardization was in progress. the first standardized version of http, http/1.1 was published in early 1997, only a few months after http/1.0. http/1.1 clarified ambiguities and introduced numerous improvements: a connection can be reused, saving the time to reopen it numerous times to display the resources embedded into the single ...
.... the first standardized version of http, http/1.1 was published in early 1997, only a few months after http/1.0. http/1.1 clarified ambiguities and introduced numerous improvements: a connection can be reused, saving the time to reopen it numerous times to display the resources embedded into the single original document retrieved. pipelining has been added, allowing to send a second request before the answer for the first one is fully transmitted, lowering the latency of the communication. chunked responses are now also supported. additional cache control mechanisms have been introduced. content negotiation, including language, encoding, or type, has been introduced, and allows a client and a server to agree on the most adequate content to exchange. thanks to the host header, the abili...
Connection management in HTTP/1.x - HTTP
herein an http/1.1 connection is upgraded to a different protocol, such as tls/1.0, websocket, or even http/2 in cleartext. this protocol upgrade mechanism is documented in more detail elsewhere. short-lived connections the original model of http, and the default one in http/1.0, is short-lived connections. each http request is completed on its own connection; this means a tcp handshake happens before each http request, and these are serialized. the tcp handshake itself is time-consuming, but a tcp connection adapts to its load, becoming more efficient with more sustained (or warm) connections. short-lived connections do not make use of this efficiency feature of tcp, and performance degrades from optimum by persisting to transmit over a new, cold connection. this model is the default model ...
...ning is subject to the hol problem. for these reasons, pipelining has been superseded by a better algorithm, multiplexing, that is used by http/2. by default, http requests are issued sequentially. the next request is only issued once the response to the current request has been received. as they are affected by network latencies and bandwidth limitations, this can result in significant delay before the next request is seen by the server. pipelining is the process to send successive requests, over the same persistent connection, without waiting for the answer. this avoids latency of the connection. theoretically, performance could also be improved if two http requests were to be packed into the same tcp message. the typical mss (maximum segment size), is big enough to contain several simple...
List of default Accept values - HTTP
initiated via the address bar of a browser, or via an html <a> element. user agent value comment firefox text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8 (since firefox 66) text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8 (in firefox 65) text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8 (before) in firefox 65 and earlier, this value can be modified using the network.http.accept.default parameter. (source) safari, chrome text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8 (source) safari 5 text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8 this is an improvement over earlier accept heade...
...e/png, image/webp, image/jpeg, image/gif, image/x-xbitmap, */*;q=0.1 values for an image when requesting an image, like through an html <img> element, user-agent often sets a specific list of media types to be welcomed. user agent value comment firefox image/webp,*/* (since firefox 65) */* (since firefox 47) image/png,image/*;q=0.8,*/*;q=0.5 (before) this value can be modified using the image.http.accept parameter. source safari */* chrome image/webp,image/apng,image/*,*/*;q=0.8 source internet explorer 8 or earlier */* see ie and the accept header (ieinternals' msdn blog) internet explorer 9 image/png,image/svg+xml,image/*;q=0.8, */*;q=0.5 see fiddler is better with interne...
Cache-Control - HTTP
che, even if the response is normally non-cacheable. if you mean to not store the response in any cache, use no-store instead. this directive is not effective in preventing caches from storing your response. no-cache the response may be stored by any cache, even if the response is normally non-cacheable. however, the stored response must always go through validation with the origin server first before using it, therefore, you cannot use no-cache in-conjunction with immutable. if you mean to not store the response in any cache, use no-store instead. this directive is not effective in preventing caches from storing your response. no-store the response may not be stored in any cache. although other directives may be set, this alone is the only directive you need in preventing cached responses o...
...ssive caching by sending the response header below. this includes static files that are served by the application such as images, css files and javascript files, for example. in addition, see also the expires header. cache-control: public, max-age=604800, immutable requiring revalidation specifying no-cache or max-age=0 indicates that clients can cache a resource and must revalidate each time before using it. this means http request occurs each time, but it can skip downloading http body if the content is valid. cache-control: no-cache cache-control: no-cache, max-age=0 specifications specification status comment rfc 8246: http immutable responses ietf rfc rfc 7234: hypertext transfer protocol (http/1.1): caching ietf rfc rfc 58...
CSP: upgrade-insecure-requests - HTTP
http content-security-policy (csp) upgrade-insecure-requests directive 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 sites with large numbers of insecure legacy urls that need to be rewritten. the upgrade-insecure-requests directive is evaluated before block-all-mixed-content and if it is set, the latter is effectively a no-op. it is recommended to set either directive, but not both, unless you want to force https on older browsers that do not force it after a redirect to http. the upgrade-insecure-requests directive will not ensure that users visiting your site via links on third-party sites will be upgraded to https for the top-level navigat...
...p-equiv="content-security-policy" content="upgrade-insecure-requests"> with the above header set on a domain example.com that wants to migrate from http to https, non-navigational insecure resource requests are automatically upgraded (first-party as well as third-party requests). <img src="http://example.com/image.png"> <img src="http://not-example.com/image.png"> these urls will be rewritten before the request is made, meaning that no insecure requests will hit the network. note that, if the requested resource is not actually available via https, the request will fail without any fallback to http. <img src="https://example.com/image.png"> <img src="https://not-example.com/image.png"> navigational upgrades to third-party resources brings a significantly higher potential for breakage, these...
If-None-Match - HTTP
hen used in combination with if-modified-since, if-none-match has precedence (if the server supports it). there are two common use cases: for get and head methods, to update a cached entity that has an associated etag. for other methods, and in particular for put, if-none-match used with the * value can be used to save a file not known to exist, guaranteeing that another upload didn't happen before, losing the data of the previous put; this problem is a variation of the lost update problem. header type request header forbidden header name no syntax if-none-match: "<etag_value>" if-none-match: "<etag_value>", "<etag_value>", … if-none-match: * directives <etag_value> entity tags uniquely representing the requested resources. they are a string of ascii...
...double quotes (like "675af34563dc-tr34") and may be prefixed by w/ to indicate that the weak comparison algorithm should be used (this is useless with if-none-match as it only uses that algorithm). * the asterisk is a special value representing any resource. they are only useful when uploading a resource, usually with put, to check if another resource with the identity has already been uploaded before. examples if-none-match: "bfc13a64729c4290ef5b2c2730249c88ca92d82d" if-none-match: w/"67ab43", "54ed21", "7892dd" if-none-match: * specifications specification title rfc 7232, section 3.2: if-none-match hypertext transfer protocol (http/1.1): conditional requests ...
Index - HTTP
Web › HTTP › Headers › Index
found 122 pages: # page tags and summary 1 http headers http, http header, networking, overview, reference http headers allow the client and the server to pass additional information with the request or the response. an http header consists of its case-insensitive name followed by a colon ':', then by its value (without line breaks). 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. using content negotiation, the server then selects one of the proposals, uses it and informs the client of its choice with the content-type response header. browsers set adequate values ...
...er-policy http, http header, privacy, reference, referrer-policy, response, referrer the referrer-policy http header governs which referrer information, sent in the referer header, should be included with requests made. 96 retry-after http, reference, response, response header, header the retry-after response http header indicates how long the user agent should wait before making a follow-up request. there are three main cases this header is used: 97 sec-websocket-accept draft, http, needscompattable, needscontent, reference, sec-websocket-accept, websockets, header the sec-websocket-accept header is used in the websocket opening handshake. it would appear in the response headers. that is, this is header is sent from server to client to inform ...
HTTP headers - HTTP
Web › HTTP › Headers
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. ...
...r that the page being loaded is going to want to perform a large allocation. link the link entity-header field provides a means for serialising one or more links in http headers. it is semantically equivalent to the html <link> element. push-policy a push-policy defines the server behaviour regarding push when processing a request. retry-after indicates how long the user agent should wait before making a follow-up request. signature the signature header field conveys a list of signatures for an exchange, each one accompanied by information about how to determine the authority of and refresh that signature. signed-headers the signed-headers header field identifies an ordered list of response header fields to include in a signature. server-timing communicates one or more metrics ...
CSS Houdini
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. in addition, layout, paint, and composite processes are repeated for javascript style updates. houdini code doesn't wait for that first rendering cycle to be complete. rather, it is included in that first cycle — creating renderable, understandable styles. houdini provides an object-based api for working with css values in javascript. houdini's css ...
...eat responsibility! with houdini you could invent your own masonry, grid, or regions implementation, but doing so is not necessarily the best idea. the css working group does a lot of work to ensure every feature is performant, handles all edge cases, and considers security, privacy, and accessibility. as you extend css with houdini, make sure to keep these considerations in mind, and start small before moving on to more ambitious projects. the houdini apis below you can find links to the main reference pages covering the apis that fall under the houdini umbrella, along with links to guides to help you if you need guidance in learning how to use them. start by reading houdini, an introduction — this provides a brief history of houdini and an overview of its many features. css parser a...
Equality comparisons and sameness - JavaScript
eir handling of primitives; none of them compares whether the parameters are conceptually similar in structure. for any non-primitive objects x and y which have the same structure but are distinct objects themselves, all of the above forms will evaluate to false. strict equality using === strict equality compares two values for equality. neither value is implicitly converted to some other value before being compared. if the values have different types, the values are considered unequal. if the values have the same type, are not numbers, and have the same value, they're considered equal. finally, if both values are numbers, they're considered equal if they're both not nan and are the same value, or if one is +0 and one is -0. var num = 0; var obj = new string('0'); var str = '0'; console.log(...
...its behavior is equivalent to +a (the unary + operator). toprimitive(a) attempts to convert its object argument to a primitive value, by attempting to invoke varying sequences of a.tostring and a.valueof methods on a. traditionally, and according to ecmascript, all objects are loosely unequal to undefined and null. but most browsers permit a very narrow class of objects (specifically...
Concurrency model and the event loop - JavaScript
message in the queue (if there is one). event loop the event loop got its name because of how it's usually implemented, which usually resembles: while (queue.waitformessage()) { queue.processnextmessage() } queue.waitformessage() waits synchronously for a message to arrive (if one is not already available and waiting to be handled). "run-to-completion" each message is processed completely before any other message is processed. this offers some nice properties when reasoning about your program, including the fact that whenever a function runs, it cannot be pre-empted and will run entirely before any other code runs (and can modify data the function manipulates). this differs from c, for instance, where if a function runs in a thread, it may be stopped at any point by the runtime system t...
... break; } } zero delays zero delay doesn't actually mean the call back will fire-off after zero milliseconds. calling settimeout with a delay of 0 (zero) milliseconds doesn't execute the callback function after the given interval. the execution depends on the number of waiting tasks in the queue. in the example below, the message ''this is just a message'' will be written to the console before the message in the callback gets processed, because the delay is the minimum time required for the runtime to process the request (not a guaranteed time). basically, the settimeout needs to wait for all the code for queued messages to complete even though you specified a particular time limit for your settimeout. (function() { console.log('this is the start'); settimeout(function cb() { ...
Grammar and types - JavaScript
contexts. for example: var n = null; console.log(n * 32); // will log 0 to the console variable scope when you declare a variable outside of any function, it is called a global variable, because it is available to any other code in the current document. when you declare a variable within a function, it is called a local variable, because it is available only within that function. javascript before ecmascript 2015 does not have block statement scope. rather, a variable declared within a block is local to the function (or global scope) that the block resides within. for example, the following code will log 5, because the scope of x is the global context (or the function context if the code is part of a function). the scope of x is not limited to the immediate if statement block. if (true) ...
... var myvar = 'my value'; (function() { var myvar; console.log(myvar); // undefined myvar = 'local value'; })(); because of hoisting, all var statements in a function should be placed as near to the top of the function as possible. this best practice increases the clarity of the code. in ecmascript 2015, let and const are hoisted but not initialized. referencing the variable in the block before the variable declaration results in a referenceerror, because the variable is in a "temporal dead zone" from the start of the block until the declaration is processed. console.log(x); // referenceerror let x = 3; function hoisting in the case of functions, only function declarations are hoisted—but not the function expressions. /* function declaration */ foo(); // "bar" function foo() { ...
Indexed collections - JavaScript
] arr.length = 42 calling array(n) results in a rangeerror, if n is a non-whole number whose fractional portion is non-zero. the following example illustrates this behavior. let arr = array(9.3) // rangeerror: invalid array length if your code needs to create arrays with single elements of an arbitrary data type, it is safer to use array literals. alternatively, create an empty array first before adding the single element to it. in es2015, you can use the array.of static method to create arrays with single element. let wisenarray = array.of(9.3) // wisenarray contains only one element 9.3 referring to array elements because elements are also properties, you can access the using property accessors. suppose you define the following array: let myarray = ['wind', 'rain', 'fire'] you ...
...logs 1 // now try again, starting from after the last match console.log(a.indexof('b', 2)) // logs 3 console.log(a.indexof('z')) // logs -1, because 'z' was not found lastindexof(searchelement[, fromindex]) works like indexof, but starts at the end and searches backwards. let a = ['a', 'b', 'c', 'd', 'a', 'b'] console.log(a.lastindexof('b')) // logs 5 // now try again, starting from before the last match console.log(a.lastindexof('b', 4)) // logs 1 console.log(a.lastindexof('z')) // logs -1 foreach(callback[, thisobject]) executes callback on every array item and returns undefined. let a = ['a', 'b', 'c'] a.foreach(function(element) { console.log(element) }) // logs each item in turn map(callback[, thisobject]) returns a new array of the return value from executing callba...
Loops and iteration - JavaScript
et btn = document.getelementbyid('btn'); btn.addeventlistener('click', function() { alert('number of options selected: ' + howmany(document.selectform.musictypes)); }); </script> do...while statement the do...while statement repeats until a specified condition evaluates to false. a do...while statement looks as follows: do statement while (condition); statement is always executed once before the condition is checked. (to execute multiple statements, use a block statement ({ ... }) to group those statements.) if condition is true, the statement executes again. at the end of every execution, the condition is checked. when the condition is false, execution stops, and control passes to the statement following do...while. example in the following example, the do loop iterates at least ...
... let i = 0; do { i += 1; console.log(i); } while (i < 5); while statement a while statement executes its statements as long as a specified condition evaluates to true. a while statement looks as follows: while (condition) statement if the condition becomes false, statement within the loop stops executing and control passes to the statement following the loop. the condition test occurs before statement in the loop is executed. if the condition returns true, statement is executed and the condition is tested again. if the condition returns false, execution stops, and control is passed to the statement following while. to execute multiple statements, use a block statement ({ ... }) to group those statements. example 1 the following while loop iterates as long as n is less than 3: let...
Inheritance and the prototype chain - JavaScript
es" we simulate are just a function object. you probably already noticed that our function a has a special property called prototype. this special property works with the javascript new operator. the reference to the prototype object is copied to the internal [[prototype]] property of the new instance. for example, when you do var a1 = new a(), javascript (after creating the object in memory and before running function a() with this defined to it) sets a1.[[prototype]] = a.prototype. when you then access properties of the instance, javascript first checks whether they exist on that object directly, and if not, it looks in [[prototype]]. this means that all the stuff you define in prototype is effectively shared by all instances, and you can even later change parts of prototype and have the chan...
...object(); o.[[prototype]] = foo.prototype; foo.call(o); (or something like that) and when you later do o.someprop; it checks whether o has a property someprop. if not, it checks object.getprototypeof(o).someprop, and if that doesn't exist it checks object.getprototypeof(object.getprototypeof(o)).someprop, and so on. in conclusion it is essential to understand the prototypal inheritance model before writing complex code that makes use of it. also, be aware of the length of the prototype chains in your code and break them up if necessary to avoid possible performance problems. further, the native prototypes should never be extended unless it is for the sake of compatibility with newer javascript features. ...
constructor - JavaScript
itializing an object of that class. the source for this interactive example is stored in a github repository. if 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 constructor([arguments]) { ... } description a constructor enables you to provide any custom initialization that must be done before any other methods can be called on an instantiated object. class person { constructor(name) { this.name = name; } introduce() { console.log(`hello, my name is ${this.name}`); } } const otto = new person('otto'); otto.introduce(); if you don't provide your own constructor, then a default constructor will be supplied for you. if your class is a base class, the default constru...
...class will throw a syntaxerror error. examples using the constructor method this code snippet is taken from the classes sample (live demo). class square extends polygon { constructor(length) { // here, it calls the parent class' constructor with lengths // provided for the polygon's width and height super(length, length); // note: in derived classes, `super()` must be called before you // can use `this`. leaving this out will cause a referenceerror. this.name = 'square'; } get area() { return this.height * this.width; } set area(value) { this.height = value**0.5; this.width = value**0.5; } } another example here the prototype of square class is changed—but the constructor of its base class polygon is still called when a new instance of a ...
ReferenceError: reference to undefined property "x" - JavaScript
the property accessors reference page to learn more about them. examples invalid cases in this case, the property bar is an undefined property, so a referenceerror will occur. ...
...ined property "bar" valid cases to avoid the error, you need to either add a definition for bar to the object or check for the existence of the bar property before trying to access it; one way to do that is to use the object.prototype.hasownproperty() method), like this: var foo = {}; // define the bar property foo.bar = 'moon'; console.log(foo.bar); // "moon" // test to be sure bar exists before accessing it if (foo.hasownproperty('bar')) { console.log(foo.bar); } ...
JavaScript error reference - JavaScript
are deprecatedsyntaxerror: "use strict" not allowed in function with non-simple parameterssyntaxerror: "x" is a reserved identifiersyntaxerror: json.parse: bad parsingsyn...
...operatorsyntaxerror: missing variable namesyntaxerror: missing } after function bodysyntaxerror: missing } after property listsyntaxerror: redeclaration of formal parameter "x"syntaxerror: return not in functionsyntaxerror: test for eq...
Functions - JavaScript
he same syntax as a function declaration (see function expression for details). a function expression may be a part of a larger expression. one can define "named" function expressions (where the name of the expression might be used in the call stack for example) or "anonymous" function expressions. function expressions are not hoisted onto the beginning of the scope, therefore they cannot be used before they appear in the code. function [name]([param[, param[, ... param]]]) { statements } name the function name. can be omitted, in which case the function becomes known as an anonymous function. param the name of an argument to be passed to the function. statements the statements comprising the body of the function. here is an example of an anonymous function expression (the name...
...puts: function anonymous() { } since the function actually does not have a name, anonymous is not a variable that can be accessed within the function. for example, the following would result in an error: var foo = new function("alert(anonymous);"); foo(); unlike functions defined by function expressions or by the function constructor, a function defined by a function declaration can be used before the function declaration itself. for example: foo(); // alerts foo! function foo() { alert('foo!'); } a function defined by a function expression or by a function declaration inherits the current scope. that is, the function forms a closure. on the other hand, a function defined by a function constructor does not inherit any scope other than the global scope (which all functions inherit). ...
Array.prototype.filter() - JavaScript
a thisarg parameter is provided to filter, it will be used as the callback's this value. otherwise, the value undefined will be used as its this value. the this value ultimately observable by callback is determined according to the usual rules for determining the this seen by a function. filter() does not mutate the array on which it is called. the range of elements processed by filter() is set before the first invocation of callback. elements which are appended to the array (from callback) after the call to filter() begins will not be visited by callback. if existing elements of the array are deleted 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 ...
... ...
Array.prototype.shift() - JavaScript
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. ...
...perties may not behave in any meaningful manner. array.prototype.pop() has similar behavior to shift, but applied to the last element in an array. examples removing an element from an array the following code displays the myfish array before and after removing its first element. it also displays the removed element: var myfish = ['angel', 'clown', 'mandarin', 'surgeon']; console.log('myfish before:', json.stringify(myfish)); // myfish before: ['angel', 'clown', 'mandarin', 'surgeon'] var shifted = myfish.shift(); console.log('myfish after:', myfish); // myfish after: ['clown', 'mandarin', 'surgeon'] console.log('removed this element:', shifted); // removed this element: angel using shift() method in while loop the shift() method is often used in condition inside while loop. in the fo...
Array.prototype.sort() - JavaScript
e. firstel the first element for comparison. secondel the second element for comparison. return value the sorted array. note that the array is sorted in place, and no copy is made. description if comparefunction is not supplied, all non-undefined array elements are sorted by converting them to strings and comparing strings in utf-16 code units order. for example, "banana" comes before "cherry". in a numeric sort, 9 comes before 80, but because numbers are converted to strings, "80" comes before "9" in the unicode order. all undefined elements are sorted to the end of the array. note : in utf-16, unicode characters above \uffff are encoded as two surrogate code units, of the range \ud800-\udfff. the value of each code unit is taken separately into account for the comparison. ...
... 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). ...
Array.prototype.splice() - JavaScript
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 elements to insert differs from the number of elements being removed, the array's length will be changed. ...
...ents to insert differs from the number of elements being removed, the array's length will be changed. ...
Function.length - JavaScript
. property attributes of function.length writable no enumerable no configurable yes description length is a property of a function object, and indicates how many arguments the function expects, i.e. the number of formal parameters. this number excludes the rest parameter and only includes parameters before the first one with a default value. by contrast, arguments.length is local to a function and provides the number of arguments actually passed to the function. data property of the function constructor the function constructor is itself a function object. its length data property has a value of 1. the property attributes are: writable: false, enumerable: false, configurable: true. property of t...
...a value of 0. examples using function length console.log(function.length); /* 1 */ console.log((function() {}).length); /* 0 */ console.log((function(a) {}).length); /* 1 */ console.log((function(a, b) {}).length); /* 2 etc. */ console.log((function(...args) {}).length); // 0, rest parameter is not counted console.log((function(a, b = 1, c) {}).length); // 1, only parameters before the first one with // a default value is counted specifications specification ecmascript (ecma-262)the definition of 'function.length' in that specification. ...
Intl.Collator() constructor - JavaScript
lower", or "false" (use the locale's default); 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. examples using collator the following example demonstrates the different potential results for a string occurring before, after, or at the same level as another: console.log(new intl.collator().compare('a', 'c')); // → a negative value console.log(new intl.collator().compare('c', 'a')); // → a positive value console.log(new intl.collator().compare('a', 'a')); // → 0 note that the results shown in the code above can vary between browsers and browser versions. this is because the values are implementation-sp...
... specifications specification ecmascript internationalization api (ecma-402)the definition of 'intl.collator constructor' in that specification. ...
Intl.Collator - JavaScript
e.compare getter function that compares two strings according to the sort order of this intl.collator object. intl.collator.prototype.resolvedoptions() returns a new object with properties reflecting the locale and collation options computed during initialization of the object. examples using collator the following example demonstrates the different potential results for a string occurring before, after, or at the same level as another: console.log(new intl.collator().compare('a', 'c')); // → a negative value console.log(new intl.collator().compare('c', 'a')); // → a positive value console.log(new intl.collator().compare('a', 'a')); // → 0 note that the results shown in the code above can vary between browsers and browser versions. this is because the values are implementation-sp...
... intl.collator().compare('a', 'c')); // → a negative value console.log(new intl.collator().compare('c', 'a')); // → a positive value console.log(new intl.collator().compare('a', 'a')); // → 0 note that the results shown in the code above can vary between browsers and browser versions. this is because the values are implementation-specific. that is, the specification requires only that the before and after values are negative and positive. using locales the results provided by collator.prototype.compare() vary between languages. in order to get the sort order of the language used in the user interface of your application, make sure to specify that language (and possibly some fallback languages) using the locales argument: // in german, ä sorts with a console.log(new intl.collator('de'...
JSON.parse() - JavaScript
the json.parse() method parses a json string, constructing the javascript value or object described by the string. an optional reviver function can be provided to perform a transformation on the resulting object before it is returned. the source for this interactive example is stored in a github repository. if 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.parse(text[, reviver]) parameters text the string to parse as json. see the json object for a description of json syntax. reviver optional if a function, this prescribes how the value originally produced by parsing is transformed, before being returned. return value the object, array, string, number, boolean, or null ...
...rown. throw new syntaxerror("json.parse"); }; } examples using json.parse() json.parse('{}'); // {} json.parse('true'); // true json.parse('"foo"'); // "foo" json.parse('[1, 5, "false"]'); // [1, 5, "false"] json.parse('null'); // null using the reviver parameter if a reviver is specified, the value computed by parsing is transformed before being returned. specifically, the computed value and all its properties (beginning with the most nested properties and proceeding to the original value itself) are individually run through the reviver. then it is called, with the object containing the property being processed as this, and with the property name as a string, and the property value as arguments. if the reviver function returns unde...
Number.prototype.toExponential() - JavaScript
clone https://github.com/mdn/interactive-examples and send us a pull request. syntax numobj.toexponential([fractiondigits]) parameters fractiondigits optional. an integer specifying the number of digits after the decimal point. defaults to as many digits as necessary to specify the number. return value a string representing the given number object in exponential notation with one digit before the decimal point, rounded to fractiondigits digits after the decimal point. exceptions rangeerror if fractiondigits is too small or too large. values between 0 and 20, inclusive, will not cause a rangeerror. implementations are allowed to support larger and smaller values as well. typeerror if this method is invoked on an object that is not a number. description if the fractiondigits a...
...ell. typeerror if this method is invoked on an object that is not a number. description if the fractiondigits argument is omitted, the number of digits after the decimal point defaults to the number of digits necessary to represent the value uniquely. if you use the toexponential() method for a numeric literal and the numeric literal has no exponent and no decimal point, leave whitespace(s) before the dot that precedes the method call to prevent the dot from being interpreted as a decimal point. if a number has more digits than requested by the fractiondigits parameter, the number is rounded to the nearest number represented by fractiondigits digits. see the discussion of rounding in the description of the tofixed() method, which also applies to toexponential(). examples using toexponen...
Object.freeze() - JavaScript
read-only (as are those of an arraybuffer or sharedarraybuffer), there is no reason for attempting to freeze these properties. comparison to object.seal() objects sealed with object.seal() can have their existing properties changed. existing properties in objects frozen with object.freeze() are made immutable. examples freezing objects var obj = { prop: function() {}, foo: 'bar' }; // before freezing: new properties may be added, // and existing properties may be changed or removed obj.foo = 'baz'; obj.lumpy = 'woof'; delete obj.prop; // freeze. var o = object.freeze(obj); // the return value is just the same object we passed in. o === obj; // true // the object has become frozen. object.isfrozen(obj); // === true // now any changes will fail obj.foo = 'quux'; // silently does no...
...receives a path (e.g. an array) argument so you can suppress calling deepfreeze() recursively when an object is in the process of being made immutable. you still run a risk of freezing an object that shouldn't be frozen, such as [window]. ...
Object - JavaScript
when a function is called, the arguments to the call are held in the array-like "variable" arguments. for example, in the call myfn(a, b, c), the arguments within myfn's body will contain 3 array-like elements corresponding ...
...jects 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-conditionally execute custom logic before the built-in logic or someone else's extension is executed. when a function is called, the arguments to the call are held in the array-like "variable" arguments. for example, in the call myfn(a, b, c), the arguments within myfn's body will contain 3 array-like elements corresponding to (a, b, c). when modifying prototypes with hooks, pass this and the arguments (the call state) to the current b...
String.prototype.split() - JavaScript
array in javascript?” on stackoverflow. limit optional a non-negative integer limiting the number of pieces. if provided, splits the string at each occurrence of the specified separator, but stops when limit entries have been placed in the array. any leftover text is not included in the array at all. the array may contain fewer entries than limit if the end of the string is reached before the limit is reached. if limit is 1, str.split(separator)[0] is returned if limit is 0, [] is returned. return value an array of strings, split at each point where the separator occurs in the given string. description when found, separator is removed from the string, and the substrings are returned in an array. if separator is a regular expression with capturing parentheses, then ea...
...ty string, rather than an empty array. if the string and separator are both empty strings, an empty array is returned. const mystring = '' const splits = mystring.split() console.log(splits) // ↪ [""] the following example defines a function that splits a string into an array of strings using separator. after splitting the string, the function logs messages indicating the original string (before the split), the separator used, the number of elements in the array, and the individual array elements. function splitstring(stringtosplit, separator) { const arrayofstrings = stringtosplit.split(separator) console.log('the original string is: ', stringtosplit) console.log('the separator is: ', separator) console.log('the array has ', arrayofstrings.length, ' elements: ', arrayofstrings...
undefined - JavaScript
null, while strict equality doesn't. this is because null is not equivalent to undefined. see comparison operators for details. typeof operator and undefined alternatively, typeof can be used: var x; if (typeof x === 'undefined') { // these statements execute } one reason to use typeof is that it does not throw an error if the variable has not been declared. // x has not been declared before if (typeof x === 'undefined') { // evaluates to true without errors // these statements execute } if (x === undefined) { // throws a referenceerror } however, there is another alternative. javascript is a statically scoped language, so knowing if a variable is declared can be read by seeing whether it is declared in an enclosing context. the global scope is bound to the global object, ...
... ...
Grouping operator ( ) - 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 ( ) description the grouping operator consists of a pair of parentheses around an expression or sub-expression to override the normal operator precedence so that expressions with lower precedence can be evaluated before an expression with higher priority. as it sounds, it groups what's inside of the parentheses. examples using the grouping operator overriding multiplication and division first, then addition and subtraction to evaluate addition first. var a = 1; var b = 2; var c = 3; // default precedence a + b * c // 7 // evaluated by default like this a + (b * c) // 7 // now overriding precedence //...
...sion with higher priority. as it sounds, it groups what's inside of the parentheses. examples using the grouping operator overriding multiplication and division first, then addition and subtraction to evaluate addition first. var a = 1; var b = 2; var c = 3; // default precedence a + b * c // 7 // evaluated by default like this a + (b * c) // 7 // now overriding precedence // addition before multiplication (a + b) * c // 9 // which is equivalent to a * c + b * c // 9 specifications specification ecmascript (ecma-262)the definition of 'the grouping operator' in that specification. ...
Optional chaining (?.) - JavaScript
nnected objects when it's possible that a reference or function may be undefined or null. for example, consider an object obj which has a nested structure. without optional chaining, looking up a deeply-nested subproperty requires validating the references in between, such as: let nestedprop = obj.first && obj.first.second; the value of obj.first is confirmed to be non-null (and non-undefined) before then accessing the value of obj.first.second. this prevents the error that would occur if you simply accessed obj.first.second directly without testing obj.first. with the optional chaining operator (?.), however, you don't have to explicitly test and short-circuit based on the state of obj.first before trying to access obj.first.second: let nestedprop = obj.first?.second; by using the ?. oper...
...if obj.first is null or undefined, the expression automatically short-circuits, returning undefined. ...
Property accessors - JavaScript
object = {}; object.$1 = 'foo'; console.log(object.$1); // 'foo' object.1 = 'bar'; // syntaxerror console.log(object.1); // syntaxerror here, the method named createelement is retrieved from document and is called. document.createelement('pre') if you use a method for a numeric literal, and the numeric literal has no exponent and no decimal point, you should leave white-space(s) before the dot preceding the method call, so that the dot is not interpreted as a decimal point. 77 .toexponential() // or 77 .toexponential() // or ;(77).toexponential() // or 77..toexponential() // or 77.0.toexponential() // because 77. === 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...
...ponential() // because 77. === 77.0, no ambiguity bracket notation in the object[property_name] syntax, the property_name is just a string or symbol. so, it can be any string, including '1foo', '!bar!', or even ' ' (a space). const variable = object[property_name] object[property_name] = value; this does the exact same thing as the previous example. document['createelement']('pre') a space before bracket notation is allowed. document ['createelement']('pre') property names property names are string or symbol. any other value, including a number, is coerced to a string. this outputs 'value', since 1 is coerced into '1'. let object = {} object['1'] = 'value' console.log(object[1]) this also outputs 'value', since both foo and bar are converted to the same string. let foo = {unique_pr...
super - JavaScript
the super keyword is used to access and call functions on an object's parent. the super.prop and super[expr] expressions are valid in any method definition in both classes and object literals. syntax super([arguments]); // calls the parent constructor. super.functiononparent([arguments]); description when used in a constructor, the super keyword appears alone and must be used before the this keyword is used. the super keyword can also be used to call functions on a parent object. examples using super in classes this code snippet is taken from the classes sample (live demo). here super() is called to avoid duplicating the constructor parts' that are common between rectangle and square. class rectangle { constructor(height, width) { this.name = 'rectangle'; this.height = heigh...
...leaving this out will cause a reference error. this.name = 'square'; } } super-calling static methods you are also able to call super on static methods. class rectangle { constructor() {} static lognbsides() { return 'i have 4 sides'; } } class square extends rectangle { constructor() {} static logdescription() { return super.lognbsides() + '...
typeof - JavaScript
used for determining the data type of expressions. let idata = 99; typeof idata + ' wisen'; // 'number wisen' typeof (idata + ' wisen'); // 'string' regular expressions callable regular expressions were a non-standard addition in some browsers. ...
...block scoped variables are in a "temporal dead zone" from the start of the block until the initialization is processed, during which, it will throw an error if accessed. ...
async function - JavaScript
await will wait for the first one to finish. in this case, the result of the fastest timer is processed after the slowest. if you wish to safely perform two or more jobs in parallel, you must await a call to promise.all, or promise.allsettled. error handling note that functions concurrentstart and concurrentpromise are not functionally equivalent. in concurrentstart, if promise fast rejects before promise slow is fulfilled, then an unhandled promise rejection error will be raised, regardless of whether the caller has configured a catch clause. in concurrentpromise, promise.all wires up the promise chain in one go, meaning that the operation will fail-fast regardless of the order of rejection of the promises, and the error will always occur within the configured promise chain, enabling it ...
...ker(v) would have caused the promise returned by the function to reject, instead of resolving to null if processdatainworker(v) rejects. this highlights the subtle difference between return foo; and return await foo; — return foo immediately returns foo and never throws, even if foo is a promise that rejects. return await foo will wait for foo to resolve or reject if it's a promise, and throws before returning if it rejects. specifications specification ecmascript (ecma-262)the definition of 'async function' in that specification. ...
class - JavaScript
class declaration is executed in strict mode. the constructor method is optional. class declarations are not hoisted (unlike function declarations). examples a simple class declaration in the following example, we first define a class named polygon, then extend it to create a class named square. note that super(), used in the constructor, can only be used in constructors, and must be called before the this keyword can be used. class polygon { constructor(height, width) { this.name = 'polygon'; this.height = height; this.width = width; } } class square extends polygon { constructor(length) { super(length, length); this.name = 'square'; } } attempting to declare a class twice re-declaring a class using the class declaration throws a syntaxerror. class foo {};...
....width = width; } } class square extends polygon { constructor(length) { super(length, length); this.name = 'square'; } } attempting to declare a class twice re-declaring a class using the class declaration throws a syntaxerror. class foo {}; class foo {}; // uncaught syntaxerror: identifier 'foo' has already been declared the same error is thrown when a class has been defined before using the class expression. let foo = class {}; class foo {}; // uncaught syntaxerror: identifier 'foo' has already been declared specifications specification ecmascript (ecma-262)the definition of 'class definitions' in that specification. ...
for...in - JavaScript
modified properties a for...in loop iterates over the properties of an object in an arbitrary order (see the delete operator for more on why one cannot depend on the seeming orderliness of iteration, at least in a cross-browser setting). if a property is modified in one iteration and then visited at a later time, its value in the loop is its value at that later time. a property that is deleted before it has been visited will not be visited later. properties added to the object over which iteration is occurring may either be visited or omitted from iteration. in general, it is best not to add, modify, or remove properties from the object during iteration, other than the property currently being visited. there is no guarantee whether an added property will be visited, whether a modified proper...
...properties added to the object over which iteration is occurring may either be visited or omitted from iteration. in general, it is best not to add, modify, or remove properties from the object during iteration, other than the property currently being visited. there is no guarantee whether an added property will be visited, whether a modified property (other than the current one) will be visited before or after it is modified, or whether a deleted property will be visited before it is deleted. array iteration and for...in note: for...in should not be used to iterate over an array where the index order is important. array indexes are just enumerable properties with integer names and are otherwise identical to general object properties. there is no guarantee that for...in will return the ind...
for - JavaScript
e for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax for ([initialization]; [condition]; [final-expression]) statement initialization an expression (including assignment expressions) or variable declaration evaluated once before the loop begins. typically used to initialize a counter variable. this expression may optionally declare new variables with var or let keywords. variables declared with var are not local to the loop, i.e. they are in the same scope the for loop is in. variables declared with let are local to the statement. the result of this expression is discarded. condition an expression to be evaluated befo...
...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 (;). ...
Transitioning to strict mode - JavaScript
e aims at providing guidance for developers. gradual transition strict mode has been designed so that the transition to it can be made gradually. it is possible to change each file individually and even to transition code to strict mode down to the function granularity. ...
...aring function in blocks if (a < b) { function f() {} } obvious errors declaring twice the same name for a property name in an object literal {a: 1, b: 3, a: 7} this is no longer the case in ecmascript 2015 (bug 1041128). declaring two function parameters with the same name function f(a, b, b) {} these errors are good, because they reveal plain errors or bad practices. they occur before the code is running. new runtime errors javascript used to silently fail in contexts where what was done was an error. strict mode throws in such cases. if your code base contains such cases, testing will be necessary to be sure nothing is broken. once again, it can happen at the function granularity level. setting a value to an undeclared variable function f(x) { 'use strict'; var a = 12...
JavaScript
ript or another language. intermediate understanding client-side javascript frameworks javascript frameworks are an essential part of modern front-end web development, providing developers with proven tools for building scalable, interactive web applications. 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. a re-introduction to javascript an overview for those who think they know about javascript. javascript data structures overview of available data structures in javascript. equality comparisons and sameness javascript provides three different value-comparison operations: strict equality using ===, loose equality usin...
... using ===, loose equality using ==, and the object.is() method. closures a closure is the combination of a function and the lexical environment within which that function was declared. advanced inheritance and the prototype chain explanation of the widely misunderstood and under-estimated prototype-based inheritance. strict mode strict mode defines that you can not use any variable before initializing it. it is a restricted variant of ecmascript 5, for faster performance and easier debugging. javascript typed arrays javascript typed arrays provide a mechanism for accessing raw binary data. memory management memory life cycle and garbage collection in javascript. concurrency model and event loop javascript has a concurrency model based on an "event loop". reference brows...
background_color - Web app manifests
therefore background_color should match the background-color css property in the site’s stylesheet for a smooth transition between launching the web application and loading the site's content. ...
... therefore background_color should match the background-color css property in the site’s stylesheet for a smooth transition between launching the web application and loading the site's content. ...
Authoring MathML - MathML
sentation mathml inside html5 documents: <!doctype html> <html> <head> <title>mathml in html5</title> </head> <body> <h1>mathml in html5</h1> <p> square root of two: <math> <msqrt> <mn>2</mn> </msqrt> </math> </p> </body> </html> content mathml is not supported by browsers. it's recommended to convert your content mathml markup into presentation mathml before publishing it, for example with the help of the ctop.xsl stylesheet. tools mentioned on this page generates presentation mathml. fallback for browsers without mathml support unfortunately, some browsers are not able to render mathml equations or only have a limited support. hence you will need to use a mathml polyfill to provide some fallback rendering. if you need only basic mathematical cons...
...eb site and reference them in your page header (see the copy-me.html file from the zip archive for an example). one of the advantage of jqmath over the previous scripts is that it will automatically add some simple css rules to do the mathematical layout and make the formulas readable on browsers with limited mathml support. command-line programs an alternative way is to parse the simple syntax before publishing your web pages. that is, you use command-line programs to generate them and publish these static pages on your server. pros: you get static web pages: the latex source don't need to be parsed at each page load, the mathml code is exposed to web crawlers and you can put them easily on any web server. binary programs may run faster than javascript programs and can be more sop...
Optimizing startup performance - Web Performance
with a little work. getting asynchronous here are some suggestions for how to build your startup process to be as asynchronous as possible (whether it's a new app or a port): use the defer or async attribute on script tags needed by the web application. this allows html parsers to continue processing the document, instead of having to wait until the scripts have been downloaded and executed before continuing. if you need to decode asset files (for example, decoding jpeg files and turning them into raw texture data for later use by webgl), that's great to do in workers. when dealing with data supported by the browser (for example, decoding image data), use the decoders built into the browser or device rather than rolling your own or using one from the original codebase. the provided one i...
... to try to help with the main code's startup process is to refactor the code into small pieces that can be done in chunks interspersed across multiple calls to your app's main loop, so that the main thread gets to handle input and the like. emscripten provides an api to help with this refactoring; for example, you can use emscripten_push_main_loop_blocker() to establish a function to be executed before the main thread is allowed to continue. by establishing a queue of functions to be called in sequence, you can more easily manage running bits of code without blocking the main thread. that leaves, though, the problem of having to refactor your existing code to actually work that way. that can take some time. how asynchronous should i get? it's worth keeping in mind that most browsers typicall...
Web Performance
m source to a destination. in terms of performance optimization, it's important to optimize to reduce causes of lacency and to test site performance emulating high latency to optimizer for users with lousy connections. this article explains what latency is, how it impacts performance, how to measure latency, and how to reduce it.using dns-prefetchdns-prefetch is an attempt to resolve domain names before resources get requested. this could be a file loaded later or link target a user tries to follow. beginner's tutorials the mdn web performance learning area contains modern, up-to-date tutorials covering performance essentials. start here if you are a newcomer to performance: web performance: brief overview overview of the web performance learning path. start your journey here. wh...
... show you how you can configure your tooling to use this feature in a widely compatible fashion. controlling resource delivery with resource hints browsers often know better than we do when it comes to resource prioritization and delivery however they're far from clairyovant. native browser features enable us to hint to the browser when it should connect to another server, or preload a resource before the browser knows it ever needs it. when used judiciously, this can make fast experience seem even faster. in this article, we cover native browser features like rel=preconnect, rel=dns-prefetch, rel=prefetch, and rel=preload, and how to use them to your advantage. performance budgets marketing, design, and sales needs, and developer experience, often ad bloat, third-party scripts, and other fe...
Privacy, permissions, and information security
information they share, ideally only with sites they trust. cooperation among web content, the web browser, and the web server is needed to achieve as much privacy and information security as possible. in this article, we examine how to create web content that minimizes the risk of users' personal information or imagery being obtained unexpectedly by third parties. security and privacy defined before we go into any depth about the various security and privacy features available to users on the web, let's define some important terms. personally identifiable information personally identifiable information (pii) is information which can be used, in whole or in part, to track down and/or identify a specific person. as such, pii extends beyond the web to all aspects of life. for example, if ...
...a small amount of variability to timers in order to make them less useful for identifying the user's system. privacy and security controls there are multiple layers of controls for helping to protect users against security and privacy breaches. these start at the web server, include the very communication layer used over the network, and then extend through the web browser's security offerings before reaching your web app code and the efforts it takes to secure itself and the data the user entrusts to it. there are several web technologies and features at play to manage privacy and security. the following list includes features affecting both, since many of these features are used for both. web technologies and features used to enforce security and privacy technology or feature ...
Progressive web app structure - Progressive web apps (PWAs)
in addition follows the "offline first" methodology which we will explain in detail in upcoming articles and use in our example application. there is also a new approach involving the streams api, which we'll mention briefly. app shell the app shell concept is concerned with loading a minimal user interface as soon as possible and then caching it so it is available offline for subsequent visits before then loading all the contents of the app. that way, the next time someone visits the 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. it also allows the websit...
... or pixel densities, using technologies like viewport meta tag, css media queries, flexbox, and css grid. different concept: streams an entirely different approach to server- or client-side rendering can be achieved with the streams api. with a little help from service workers, streams can greatly improve the way we parse content. the app shell model requires all the resources to be available before the website can start rendering. it's different with html, as the browser is actually streaming the data already and you can see when the elements are loaded and rendered on the website. to have the javascript "operational", however, it has to be downloaded in its entirety. the streams api allows developers to have direct access to data streaming from the server — if you want to perform an ope...
Making PWAs work offline with Service workers - Progressive web apps (PWAs)
notifications, performing heavy calculations on a separate thread, etc. service workers are quite powerful as they can take control over network requests, modify them, serve custom responses retrieved from the cache, or synthesize responses completely. security because they are so powerful, service workers can only be executed in secure contexts (meaning https). if you want to experiment first before pushing your code to production, you can always test on a localhost or setup github pages — both support https. offline first the "offline first" — or "cache first" — pattern is the most popular strategy for serving content to the user. if a resource is cached and available offline, return it first before trying to download it from the server. if it isn’t in the cache already, download ...
...onse 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 example app, we serve content from the cache instead of the network as long as the resource is actually in the cache. we do this whether the app is online or offline. ...
Structural overview of progressive web apps - Progressive web apps (PWAs)
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 before then loading the remainder of the app's contents. 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. it also allows th...
... pixel densities, using technologies like the viewport meta tag, css media queries, flexbox, and css grid. another approach: streams an entirely different approach to server- or client-side rendering can be achieved with the streams api. with a little help from service workers, streams can greatly improve the way we parse content. the app shell model requires all the resources to be available before the website can start rendering. it's different with html, as the browser is actually streaming the data already and you can see when the elements are loaded and rendered on the website. to have the javascript actually work, however, it has to be downloaded in its entirety. the streams api allows developers to have direct access to data streaming from the server. if you want to perform an operat...
Content type - SVG: Scalable Vector Graphics
ntage of the bounding box width or height on a given object. in the svg dom, <length> values are represented using svglength or svganimatedlength objects. list-of-ts <list-of-ts> (where t is some type.) a list consists of a separated sequence of values. unless explicitly described differently, lists within svg's xml attributes can be either comma-separated (with optional white space before or after the comma), or white space-separated. white space in lists is defined as one or more of the following consecutive characters: "space" (u+0020), "tab" (u+0009), "line feed" (u+000a), "carriage return" (u+000d), and "form-feed" (u+000c). the following is a template for an ebnf grammar describing the <list-of-ts> syntax: list-of-ts ::= t | t, list-of-ts within the svg...
...mations. a detailed description of the possible values for a <transform-list> is given in the transform attribute definition. within the svg dom, a <transform-list> value is represented using an svgtransformlist or svganimatedtransformlist object. url url a uniform resource locator. a url is a sequence of unicode characters, building an address to an internal or external resource. before svg 2, the more limited iri content type was used instead, because the url specification was not standardized before. ...
Namespaces crash course - SVG: Scalable Vector Graphics
his namespace declaration sets the namespace for something called a "namespace prefix". in this case, we have chosen to use the prefix xlink (the second part) since the prefix will be used to tell the user agent about attributes that belong to xlink. as their name suggests, namespace prefixes are used to prefix parameter and element names. this is done by putting the namespace prefix and a colon before the parameter name as shown on the <script> element in the example above. this tells the user agent that that particular parameter belongs to the namespace assigned to the namespace prefix (xlink), and is a parameter that can be used with the same meaning on other elements. note that it is an xml error to use a prefix that hasn't been bound to a namespace name. the binding created by the xmlns:x...
...> element and its child <svg:circle>, it wasn't necessary to redeclare the default namespace. in general though it is better to redeclare the default namespace rather than prefix lots of elements in this way. scripting in namespaced xml namespaces affect not only markup, but also scripting. if you write scripts for namespaced xml such as svg, read on. the dom level 1 recommendation was created before the original namespaces in xml recommendation was released; therefore, dom1 isn't namespace aware. this causes problems for namespaced xml such as svg. to resolve these problems, dom level 2 core added namespace aware equivalents of all the applicable dom level 1 methods. when scripting svg, it is important to use the namespace aware methods. the table below lists the dom1 methods that shouldn't ...
Getting started - SVG: Scalable Vector Graphics
vg> copy the code and paste it in a file demo1.svg. then open the file in firefox. it will render as shown in the following screenshot. (firefox users: click here) the rendering process involves the following: we start with the <svg> root element: a doctype declaration as known from (x)html should be left off because dtd based svg validation leads to more problems than it solves before svg 2, to identify the version of the svg for other types of validation the version and baseprofile attributes should always be used instead. both version and baseprofile attributes are deprecated in svg 2. as an xml dialect, svg must always bind the namespaces correctly (in the xmlns attribute). see the namespaces crash course page for more info. the background is set to red by drawing ...
... however, there may be syntax changes necessary to conform to the html5 specification. the svg file can be referenced with an object element: <object data="image.svg" type="image/svg+xml" /> likewise an iframe element can be used: <iframe src="image.svg"></iframe> an img element can theoretically be used too. however, this technique doesn't work in firefox before 4.0. finally, svg can be created dynamically with javascript and injected into the html dom. with this method, replacement 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 ...
Introduction - SVG: Scalable Vector Graphics
hic together. in addition there is the <g> element, which is used to group several basic shapes together. starting from there, the svg image can become arbitrarily complex. svg supports gradients, rotations, filter effects, animations, interactivity with javascript, and so on. but all these extra features of the language rely on this relatively small set of elements to define the graphics area. before you start there are a number of drawing applications available such as inkscape which are free and use svg as their native file format. however, this tutorial will rely on the trusty xml or text editor (your choice). the idea is to teach the internals of svg to those who want to understand it, and that is best done by dirtying your hands with a bit of markup. you should note your final goal thou...
...browsers and even a couple versions back in some cases. a fairly complete browser support table can be found on can i use. firefox has supported some svg content since version 1.5, and that support level has been growing with each release since. hopefully, along with the tutorial here, mdn can help developers keep up with the differences between gecko and some of the other major implementations. before starting you should have a basic understanding of xml or another markup language such as html. if you are not too familiar with xml, here are some guidelines to keep in mind: svg elements and attributes should all be entered in the case shown here since xml is case-sensitive (unlike html). attribute values in svg must be placed inside quotes, even if they are numbers. svg is a huge specific...
Certificate Transparency - Web security
be no need for web servers to be modified if this mechanism is used. with the latter methods, servers will need to be updated to send the required data. the advantage is that the server operator can customise the ct log sources providing the scts sent via the tls extension/stapled ocsp response. browser requirements google chrome requires ct log inclusion for all certificates issues with a notbefore date of after 30 april 2018. users will be prevented from visiting sites using non-compliant tls certificates. chrome had previously required ct inclusion for extended validation (ev) and symantec-issued certificates. apple requires a varying number of scts in order for safari and other servers to trust server certificates. firefox does not currently check or require the use of ct logs for site...
...d certificates. apple requires a varying number of scts in order for safari and other servers to trust server certificates. firefox does not currently check or require the use of ct logs for sites that users visit. the expect-ct header can be used to request that a browser always enforces the requirement for certificate transparency (e.g. in chrome, even if the certificate was issued with a notbefore date prior to april). specifications specification status comment certificate transparency ietf rfc ...
Subresource Integrity - Web security
lowing examples, assume that oqvuafxrkap7fdgccy5uykm6+r9gqq8k/uxy9rx7hnqlgyl1kpzqho1wx4jwy8wc is already known to be the expected sha-384 hash (digest) of a particular script example-framework.js, and there’s a copy of the script hosted at https://example.com/example-framework.js. subresource integrity with the <script> element you can use the following <script> element to tell a browser that before executing the https://example.com/example-framework.js script, the browser must first compare the script to the expected hash, and verify that there's a match. <script src="https://example.com/example-framework.js" integrity="sha384-oqvuafxrkap7fdgccy5uykm6+r9gqq8k/uxy9rx7hnqlgyl1kpzqho1wx4jwy8wc" crossorigin="anonymous"></script> note: for more details on the purpose of the cr...
...grity="sha384-oqvuafxrkap7fdgccy5uykm6+r9gqq8k/uxy9rx7hnqlgyl1kpzqho1wx4jwy8wc" crossorigin="anonymous"></script> note: for more details on the purpose of the crossorigin attribute, see cors settings attributes. how browsers handle subresource integrity browsers handle sri by doing the following: when a browser encounters a <script> or <link> element with an integrity attribute, before executing the script or before applying any stylesheet specified by the <link> element, the browser must first compare the script or stylesheet to the expected hash given in the integrity value. 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 sh...
Transport Layer Security - Web security
d 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 sure to review the generated configuration before using it; installing the configuration file without ensuring any references to domain names and the like are correct will result in a server that just doesn't work. tls 1.3 rfc 8446: tls 1.3 is a major revision to tls. tls 1.3 includes numerous changes that improve security and performance. the goals of tls 1.3 are: remove unused and unsafe features of tls 1.2. include strong security analy...
...ls 1.3 handshake completes in one round trip in most cases, reducing handshake latency. a server can enable a 0-rtt (zero round trip time) handshake. clients that reconnect to the server can send requests immediately, eliminating the latency of the tls handshake entirely. though the performance gains from 0-rtt can be significant, they come with some risk of replay attack, so some care is needed before enabling this feature. tls 1.3 supports forward-secure modes only, unless the connection is resumed or it uses a pre-shared key. tls 1.3 defines a new set of cipher suites that are exclusive to tls 1.3. these cipher suites all use modern authenticated encryption with associated data (aead) algorithms. the tls 1.3 handshake is encrypted, except for the messages that are necessary to establish a...
Index - XPath
Web › XPath › Index
ext node. it can be abbreviated as two periods (..). 13 preceding axe, xpath the preceding axis indicates all the nodes that precede the context node in the document except any ancestor, attribute and namespace nodes. 14 preceding-sibling axe, xpath the preceding-sibling axis indicates all the nodes that have the same parent as the context node and appear before the context node in the source document. 15 self axe, xpath the self axis indicates the context node itself. it can be abbreviated as a single period (.). 16 comparison of css selectors and xpath css, draft, needscontent, reference, selectors, xpath this article seeks to document the difference between css selectors and xpath for web developers to be able...
...e string-length function returns a number equal to the number of characters in a given string. 47 substring xslt, xslt_reference the substring function returns a part of a given string. 48 substring-after xslt, xslt_reference the substring-after function returns a string that is the rest of a given string after a given substring. 49 substring-before xslt, xslt_reference the substring-before function returns a string that is the part of a given string before a given substring. 50 sum xslt, xslt_reference the sum function returns a number that is the sum of the numeric values of each node in a given node-set. 51 system-property xslt, xslt_reference the system-property function returns an ...
Compiling a New C/C++ Module to WebAssembly - WebAssembly
n.h> int main(int argc, char ** argv) { printf("hello world\n"); } #ifdef __cplusplus extern "c" { #endif void emscripten_keepalive myfunction(int argc, char ** argv) { printf("myfunction called\n"); } #ifdef __cplusplus } #endif by default, emscripten-generated code always just calls the main() function, and other functions are eliminated as dead code. putting emscripten_keepalive before a function name stops this from happening. you also need to import the emscripten.h library to use emscripten_keepalive. note: we are including the #ifdef blocks so that if you are trying to include this in c++ code, the example will still work. due to c versus c++ name mangling rules, this would otherwise break, but here we are setting it so that it treats it as an external c function if y...
...first of all, open up your hello3.html file in a text editor. add a <button> element as shown below, just above the first opening <script type='text/javascript'> tag. <button class="mybutton">run myfunction</button> now add the following code at the end of the first <script> element: document.queryselector(...
Loading Content Scripts - Archive of obsolete content
ntentscript and contentscriptfile accept an array of strings, so you can load multiple scripts, which can also interact directly with each other in the content process: // "data" is supplied by the "self" module var data = require("sdk/self").data; ... contentscriptfile: [data.url("jquery-1.4.2.min.js"), data.url("my-content-script.js")] scripts specified using contentscriptfile are loaded before those specified using contentscript. this enables you to load a javascript library like jquery by url, then pass in a simple script inline that can use jquery. unless your content script is extremely simple and consists only of a static string, don't use contentscript: if you do, you may have problems getting your add-on approved on amo. instead, keep the script in a separate file and load it ...
Classes and Inheritance - Archive of obsolete content
he sdk uses a special constructor internally, known as class, to create constructors that behave properly with respect to inheritance. the last section shows how to work with the class constructor. it is possible to read this section on its own. however, to fully appreciate how class works, and the problem it is supposed to solve, it is recommended that you read the entire article. constructors before the ecmascript 6 standard, a javascript class was defined by creating a constructor function for that class. to illustrate this, let's define a simple constructor for a class shape: function shape(x, y) { this.x = x; this.y = y; } we can now use this constructor to create instances of shape: let shape = new shape(2, 3); shape instanceof shape; // => true shape.x; // => 2 shape.y; // =...
Private Properties - Archive of obsolete content
thin another closure, there is no way for objects of the same class to access each other's private properties. using weakmaps the techniques above are either not restrictive enough (prefixes) or too restrictive (closures), however the recent introduction of weakmaps provides a solution. weakmaps were introduced to javascript in ecmascript 2015 and have recently been implemented in spidermonkey. before explaining how weakmaps work, the following looks at how ordinary objects can be used as hash maps, by creating a simple image cache: let images = {}; function getimage(name) { let image = images[name]; if (!image) { image = loadimage(name); images[name] = image; } return image; } now suppose there's a need to associate a thumbnail with each image. moreover, to...
clipboard - Archive of obsolete content
"aabzenr0aaaasuleqvryhe3o0qkaiawd0eyqe3q993aq3cbsukpygfsnty" + "n5ugbqpk0baadgp0brdwxwlweaaaaagpsa3rzdaaaaahgpcgrpganzq2fg" + "bwrr9aaaaabjru5erkjggg%3d%3d"); if the clipboard contains an image, open it in a new tab. var clipboard = require("sdk/clipboard"); if (clipboard.currentflavors.indexof("image") != -1) require("sdk/tabs").open(clipboard.get()); as noted before, data type can be easily omitted for images. if the intention is set the clipboard to a data url as string and not as image, it can be done by specifying a different flavor, like text. var clipboard = require("sdk/clipboard"); clipboard.set("data:image/png;base64,ivborw0kggoaaaansuheugaaacaaaaagcaya" + "aabzenr0aaaasuleqvryhe3o0qkaiawd0eyqe3q993aq3cbsukpygfsnty" + "n...
request - Archive of obsolete content
request({ url: "https://api.twitter.com/1.1/application/rate_limit_status.json", oncomplete: function (response) { if (response.json.remaining_hits) { latesttweetrequest.get(); } else { console.log("you have been rate limited!"); } } }).get(); methods get() make a get request. head() make a head request. post() make a post request. put() make a p...
windows - Archive of obsolete content
that the content has loaded, only that the browser window itself is fully visible to the user. arguments window : listeners are passed the window object that triggered the event. close event emitted when a window is closed. you can't always rely on receiving the close event for every open window. in particular, if the user quits the browser then it's possible that your add-on will be unloaded before all windows are closed. arguments window : listeners are passed the window object that triggered the event. activate event emitted when an inactive window is made active. arguments window : listeners are passed the window object that has become active. deactivate event emitted when the active window is made inactive. arguments window : listeners are passed the window object that has bec...
console/plain-text - Archive of obsolete content
...
core/heritage - Archive of obsolete content
55 pink.green() // => 192 pink.blue() // => 203 // cmyk pink.magenta() // => 0.2471 pink.yellow() // => 0.2039 pink.cyan() // => 0.0000 pink instanceof color // => true be aware though that it's not multiple inheritance and ancestors prototypes of the classes passed under implements option are ignored. 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 inheritance and composition together if necessary: var point = class({ initialize: function initialize(x, y) { this.x = x; this.y = y; }, tostring: function tostring() { return this.x + ':' + this.y; } }) var pixel = class({ extends: point, ...
dev/panel - Archive of obsolete content
volcan.js: a javascript api for the debugging protocol communicating with the debugger server by exchanging json messages can be cumbersome. so we've also provided a library called volcan.js which gives you a javascript api to the remote debugging protocol. note that at the moment volcan.js does not support the complete remote debugging protocol. we're s...
net/xhr - Archive of obsolete content
't prevented, malicious code could access sensitive data. if transmission of cookies isn't prevented, malicious code could access sensitive data. attenuating access based on a regular expression may be ineffective if it's easy to write a regular expression that looks safe but contains a special character or two that makes it far less secure than it seems at first glance. possible attenuations before being exposed to unprivileged code, this object needs to be attenuated in such a way that, at the very least, it can't access the user's filesystem. this can probably be done most securely by white-listing the protocols that can be used in the url passed to the open() method, and limiting them to http:, https:, and possibly a special scheme that can be used to access the add-on's packaged, read-o...
places/bookmarks - Archive of obsolete content
nputitem) { // the `data` event returns the latest snapshot from the // host, so this is a new instance of the bookmark item, // where `item !== mybookmark`. to match it with the input item, // use the second argument, so `inputitem === mybookmark` // all explicitly saved items have data events called, as // well as implicitly saved items. in this case, // `mygroup` has to be saved before `mybookmark`, since // `mybookmark` is a child of `mygroup`. `mygroup` will // also have a `data` event called for it. }).on("end", function (items, inputitems) { // the `end` event returns all items that are explicitly // saved. so `mygroup` will not be in this array, // but `mybookmark` will be. // `inputitems` matches the initial input as an array, // so `inputitems[0] === mybook...
places/history - Archive of obsolete content
("sdk/places/history"); // simple query search( { url: "https://developers.mozilla.org/*" }, { sort: "visitcount" } ).on("end", function (results) { // results is an array of objects containing // data about visits to any site on developers.mozilla.org // ordered by visit count }); // complex query // the query objects are or'd together // let's say we want to retrieve all visits from before a week ago // with the query of 'ruby', but from last week onwards, we want // all results with 'javascript' in the url or title. // we'd compose the query with the following options let lastweek = date.now - (1000*60*60*24*7); search( // first query looks for all entries before last week with 'ruby' [{ query: "ruby", to: lastweek }, // second query searches all entries after last week with...
ui/button/action - Archive of obsolete content
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 for tab b. to delete a tab- or window-specific state, assign null to the property. ...
ui/button/toggle - Archive of obsolete content
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 for tab b. to delete a tab- or window-specific state, assign null to the property. ...
util/collection - Archive of obsolete content
a collection object provides for...in-loop iteration. items are yielded in the order they were added. for example, the following code... var collection = require("sdk/util/collection"); var c = new collection.collection(); c.add(1); c.add(2); c.add(3); for (item in c) console.log(item); ... would print this to the console: 1 2 3 iteration proceeds over a copy of the collection made before iteration begins, so it is safe to mutate the collection during iteration; doing so does not affect the results of the iteration. methods add(itemoritems) adds a single item or an array of items to the collection. any items already contained in the collection are ignored. parameters itemoritems : object an item or array of items. returns collection : the collection. remove(itemoritems) ...
cfx to jpm - Archive of obsolete content
-based and is distributed as a zip file. jpm is node-js-based and is distributed through npm. so for jpm you don't need python, but you do need npm. to get new updates of cfx you download and extract a new zip file, while to get the new version of jpm, use npm update. for jpm installation instructions, see the installation section in the jpm reference. activation you need to call cfx activate before you can use cfx, and this only works in the current command shell: if you open a new shell you have to call activate again. with jpm, you don't need to activate. once it's installed, you can just use it. add-on incompatibilities in most respects, add-ons created with cfx will work fine with jpm. however, there are a few differences you have to know about. add-on id the add-on id is a unique ...
jpm - Archive of obsolete content
validation, was signed by mozilla, and a new signed xpi was downloaded to your working directory. your add-on failed validation, was not signed, and you got a link to a detailed report. after fixing the validation errors, you can run the command again. you add-on passed validation but it could not be automatically signed because your add-on is listed. listed add-ons will require a manual review before they can be signed. your add-on at this exact version number already exists, so it was not signed. increment the version number in your package.json file and run the command again. under the hood, jpm sign creates an unlisted add-on inside addons.mozilla.org, which means you must distribute the xpi file yourself for your users to install it. if you need to create a listed add-on, just submit i...
Bookmarks - Archive of obsolete content
or the new api is available at places. the places bookmarks service, provided by the nsinavbookmarksservice interface, provides methods for creating, deleting, and manipulating bookmarks and bookmark folders. this article offers examples for how to perform common bookmark management tasks using the bookmarks service. initiating the bookmarks service as is the case with nearly all interfaces, before you can use the bookmarks service, you need to get access to it: var bmsvc = components.classes["@mozilla.org/browser/nav-bookmarks-service;1"] .getservice(components.interfaces.nsinavbookmarksservice); creating a bookmark folder creating a new bookmark folder is done using the nsinavbookmarksservice.createfolder() method. for example, to create a new folder in the bookm...
Downloading Files - Archive of obsolete content
normally, nsiauthprompt expects a prompt to be displayed so the user can enter credentials, but you can return a username and password credentials directly without prompting the user. if you want to open a login prompt, you can use ...
File I/O - Archive of obsolete content
callback); } synchronous checking the existence of a file // |file| is nsifile if (file.exists()) { // ... } note: you should avoid checking the existence of a file, not only because of the synchronous i/o on the main thread this causes. there might be races between different processes and/or threads, e.g., a file could be immediately created or deleted after you check the existence but before you can perform any other actions such as opening the file for reading or writing. reading a file // |file| is nsifile var data = ""; var fstream = components.classes["@mozilla.org/network/file-input-stream;1"]. createinstance(components.interfaces.nsifileinputstream); var cstream = components.classes["@mozilla.org/intl/converter-input-stream;1"]. createinstance(com...
Examples and demos from articles - Archive of obsolete content
possible approach to solve this problem is to nest all the informations needed by each animation to start, stop, etc. etc. in different objects and then to create a constructor for such class of objects in order to standardize and simplify the instantiation of them. here is a possible and minimalist example of such abstraction, which for this reason we named minidaemon. [article] image preview before upload [html] the filereader.prototype.readasdataurl() method is useful, for example, to get a preview of an image before uploading it. [article] note: the filereader() constructor was not supported by internet explorer for versions before 10. for a full compatibility code, see also our crossbrowser possible solution for image preview. determine if an element has been totally scrolled [html]...
HTML in XUL for rich tooltips - Archive of obsolete content
o dynamically populate the tooltip (which is about to be shown) with a different message for each menuitem. this is done by calling the onmousetooltip function, which will take the tooltiphtml attribute of the element that is being hovered over and safely convert that into dom and inject it into the tooltip that will soon be shown. the tooltiphtml attribute is an html string which is set sometime beforehand for each element. for security reasons, the conversion will strip out some of the more dangerous elements in the html string, like javascript and iframes. non-dynamic html in xul tooltip it is also possible to avoid using dynamic html to accomplish this. you would have to have a separate xul tooltip element assigned to each element that you wish to have a rich tooltip with. you should write...
Post data to window - Archive of obsolete content
the apostdata argument of the (global) loaduri(), opendialog(), and (tab)browser.loaduriwithflags() methods expects the post data in the form of an nsiinputstream (because they eventually call nsiwebnavigation.loaduri()) while post data can be created using nsimimeinputstream. most of the time, post data starts as a data string in the form of "name1=data1&name2=data2&...", so you must convert it before passing the data to one of the methods. here is an example: var datastring = "name1=data1&name2=data2"; // post method requests must wrap the encoded text in a mime // stream const cc = components.classes; const ci = components.interfaces; var stringstream = cc["@mozilla.org/io/string-input-stream;1"]. createinstance(ci.nsistringinputstream); if ("data" in stringstream) // ge...
Delayed Execution - Archive of obsolete content
e usages include: const timer = components.constructor("@mozilla.org/timer;1", "nsitimer", "initwithcallback"); function delay(timeout, func) { let timer = new timer(function () { // remove the reference so that it can be reaped. delete delay.timers[idx]; func(); }, timeout, ci.nsitimer.type_one_shot); // store a reference to the timer so that it's not reaped before it fires. let idx = delay.timers.push(timer) - 1; return idx; } delay.timers = []; function repeat(timeout, func) { let timer = new timer(function () { func(); }, timeout, ci.nsitimer.type_repeating_slack); // store a reference to the timer so that it's not reaped before it fires. let idx = delay.timers.push(timer) - 1; return idx; } repeat.timers = [...
JavaScript timers - Archive of obsolete content
s created by javascript timers or by a worker instantiation. here are some code snippets which simplify and abstract the management of daemons. requestanimationframe() requestanimationframe() tells the browser that you wish to perform an animation and requests that the browser schedule a repaint of the window for the next animation frame. the method takes as an argument a callback to be invoked before the repaint. performance.now() performance.now() returns a timestamp, measured in milliseconds, accurate to one thousandth of a millisecond. this timestamp is equal to the number of milliseconds since the navigationstart attribute of the performance.timing interface. date.now() date.now() returns the number of milliseconds elapsed since 1 january 1970 00:00:00 utc. using javascript timer...
URI parsing - Archive of obsolete content
suffixes: var etldservice = components.classes["@mozilla.org/network/effective-tld-service;1"]. getservice(components.interfaces.nsieffectivetldservice); var suffix = etldservice.getpublicsuffix(auri); var basedomain = etldservice.getbasedomain(auri); // this includes the tld basedomain = basedomain.substr(0, (basedomain.length - suffix.length - 1)); // - 1 to remove the period before the tld ...
xml:base support in old browsers - Archive of obsolete content
these two functions aim to allow some support for xml:base. note however, that this code is not based on a thorough examination of the specs related to forming base uris and could well have a number of errors. however, it is working in some of the cases tested. ...
Common Pitfalls - Archive of obsolete content
xception to all of the above, that is the one case in which creating a specific uri class via createinstance is acceptable, is when one is implementing a protocol handler's newuri method. in that case you may not be able to use the i/o service because that service calls the newuri method on the appropriate protocol handler, which may be your own handler. how to do security checks for uri loads before loading a uri, one of two security checks needs to be performed: if the uri is a string that will be loaded via passing the string to nsiwebnavigation::loaduri, the one must call checkloaduristrwithprincipal and pass the principal that the uri originates from as the first argument and the uri string as the second argument. in all other cases, one should call checkloaduriwithprincipal and pass ...
Communication between HTML and your extension - Archive of obsolete content
lag that you pass to addeventlistener but every time i would catch the event in the extension, the element from the ajax request wasn't fully updated into the html page. what that meant is that everytime the extension went looking for the element, it wasn't there yet. as a last ditch effort i tried setting a timeout using settimeout when i got the event in the extension to wait a few milliseconds before looking for the desired element. this was non-optimal and the timeout wasn't very reliable for some reason. sometimes i would get the timeout, sometimes i would'nt. what i ended up with some helpful information on the irc channel led me to believe that a custom event might help. i started to research custom events on google but everything that i found was far too complicated for what i wanted to ...
Install Manifests - Archive of obsolete content
ators. you may specify more than one of this value to specify multiple translators. examples <em:translator>janez novak</em:translator> <em:translator>kari nordmann</em:translator> unpack a true or false value that tells the application whether the extension requires its files be unpacked into a directory in order to work or whether the extension can be loaded direct from the xpi. in versions before gecko 2.0 all extensions were unpacked, in gecko 2.0 and later the default is to not unpack. if an extension includes the following then it must request unpacking: binary xpcom components plugins search plugins dlls loaded with ctypes dictionaries window icons examples <description about="urn:mozilla:install-manifest"> <em:id>extension@mysite.com</em:id> <em:unpack>true</em:unpac...
Installing Extensions and Themes From Web Pages - Archive of obsolete content
a mozilla-specific extension and so we can have special handling for it, but jar is not - not all .jar files are firefox themes, so if you click on a .jar link you'll be shown the save as decision dialog. for this reason you should always use the installtrigger api to install themes. a note on updateenabled() installtrigger exposes a function called updateenabled that some of you may be calling before you call installtrigger.install. this is not necessary as install calls updateenabled itself internally. furthermore, calling updateenabled may lead to problems if your distribution site is not in the user's whitelist, because firefox only displays the "installation blocked" message when install or installchrome are called, or when a xpi file is loaded. so, if you have code that looks like this: ...
Migrating from Internal Linkage to Frozen Linkage - Archive of obsolete content
ompare(str1, str2, comp) (str1).compare(str2, comp) #define last() endreading()[-1] #define setcharat(c, i) replace(i, 1, ch) #define ns_newisupportsarray(result) callcreateinstance(ns_supportsarray_contractid, static_cast<nsisupportsarray**>(result)); ideally we would switch to nsimutablearray, but in the mean time there's no point changing the same code twice. note: #include nsisupportsarray.h before nsmsgutils.h convenience methods that work using either api. msglowercaseequalsliteral(a8, literal) replaces (a8).lowercaseequalsliteral(literal). note that the external api provides lowercaseequalsliteral for nsastring, but not nsacstring. msgrfindchar(str, ch, len) replaces (str).rfindchar(ch, len) msgcompresswhitespace(str) replaces (str).compresswhitespace(). support for the optional parame...
Chapter 1: Introduction to Extensions - Archive of obsolete content
eviousnext » note: if you want contribute to this document please following guidelines from the contribute page. 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. what features are considered standard for web browsers these days? perhaps things like fine-grained tab controls, mouse gestures, extensive toolbars and buttons, a feed reader, integration with a variety of web applicat...
Chapter 2: Technologies used in developing extensions - Archive of obsolete content
we will also look at the minimum knowledge you'll need to have in order to develop for firefox. ...
Chapter 4: Using XPCOM—Implementing advanced processes - Archive of obsolete content
chapter. in order to set universalxpconnect privileges, you need to run the code in listing 2. listing 2: setting privileges netscape.security.privilegemanager.enableprivilege('universalxpconnect'); note: this is unneeded when the code is part of an extension, and will result in rejection if submitted to addons.mozilla.org. permit by dialog try adding the contents of listing 2 to test.xul, before the line var ioservice = …, and re-open it in firefox. you should now see the confirmation dialog shown in figure 1. pressing the "permit" button grants universalxpconnect permission in this execution context, making it possible to run xpconnect temporarily. an xpconnect-wrapped nsiioservice message should appear. if you check “apply these privileges in the future”, all local files will be...
Adding Events and Commands - Archive of obsolete content
an also be used for other elements. for more advanced event handling, you should read about event propagation. in a nutshell, events propagate from the root of the dom tree all the way down to the target element and then all the way up back to the root, in the capture and bubble phases, respectively. you can capture and cancel events during any of these phases, provided that they aren't canceled before they reach the point where you intended to capture them. the addeventlistener method allows you to control the phase where you want to handle an event, with the last argument of the function. in general, you should avoid adding event handlers in the capturing phase, or canceling events. this can lead to unexpected behavior for the user since most events have a default behavior associated to them...
Adding menus and submenus - Archive of obsolete content
e children when the popup is about to be displayed. dom functions like createelement and appendchild can be used to accomplish this. if you have nothing to show on a menu, you should follow the standard used in firefox: show a single disabled item with an "(empty)" label. if filling your menu takes a noticeable amount of time, you should not make firefox (and your users) wait for it to fill up before displaying anything. it's best to show an item with a throbber image (see chrome://global/skin/icons/loading_16.png) so the user knows there's something going on, and asynchronously fill its contents. we'll look into some asynchronous techniques further ahead in the tutorial. adding elements to existing menus just as explained in the previous sections, the best place to overlay your extension ...
Adding sidebars - Archive of obsolete content
ot nodes, giving the user the possibility to expand whichever ones are needed. trees are specially powerful when combined with data templates, a topic that will be covered later on. you can also read much more about trees in the xul tutorial page. the tree element is possibly the most complex element in xul. it is meant to be very versatile and malleable, but it can require a good amount of work before it fits your specific needs. it is in reality a hierarchical table view, so its content is defined in terms of rows and columns. here's an example of a simple tree: <tree flex="1"> <treecols> <treecol label="&xulschoolhello.namecolumn.label;" flex="1" /> <treecol label="&xulschoolhello.greetingcolumn.label;" flex="3" /> </treecols> <treechildren> <treeitem> <treerow> ...
Adding windows and dialogs - Archive of obsolete content
o associate the grouped elements with a title. the groupbox shouldn't be seen as an aesthetic device, but a logical one. if all you need is a border, use css. the groupbox element should be used when enclosed elements share some function which is separate from other elements or groups in the same window. it's also a useful accessibility feature, because screen readers will read the caption right before reading any text in its contents. you can change its style using css in case you don't want the borders to appear. see the firefox preferences window for an example of this: sections are defined using groupbox elements, but their style is quite different from the default. attribute persistence user actions can change the state of your windows, such as selecting an option in a listbox, or enteri...
Appendix B: Install and Uninstall Scripts - Archive of obsolete content
irstrunpref = "extensions.xulschoolhello.firstrundone"; if (!application.prefs.getvalue(firstrunpref, false)) { application.prefs.setvalue(firstrunpref, true); // all the rest of the first run code goes here. } } in this case you would need to declare the first run preference in your default preferences file, with a default value of false. you should also change the preference value before you run any other first run code. keep in mind that the user could have set multiple firefox windows to open at startup, so there's a race condition on which window will run the first run code. if you need to run code on every update, or some of them, the code would be very similar. instead of a boolean preference, it would be best to use a string preference with the last-installed add-on versio...
Custom XUL Elements with XBL - Archive of obsolete content
tribute lets your inner xul use the attributes that are set on the node. so, if you have this: <xshelloperson name="pete" greeting="good morning" image="" />, then those attribute values are "inherited" to the content nodes that have this special attribute. the value attribute of the xul:label element would be "pete". the oncommand attribute of the button has some code you've probably never seen before: document.getbindingparent(this). this code gets the dom object that corresponds to the xshelloperson tag, allowing you access to its methods and properties. in this case we're calling the remove method, which we will discuss later on. if you need to create a container element, or any other element that has child nodes, you can use the xbl children tag in your content to indicate the place wher...
Local Storage - Archive of obsolete content
so be complicated, but it is worth the effort if you need to display long lists or trees with complex data. if you manage to get your display code to use templates, you will have saved a lot of coding. since templates are not necessary for most extensions and they're a complicated subject, it's better that you read it from the experts. there's a very detailed xul template guide here. as mentioned before, it revolves around rdf, so you may need to take some time to understand how rdf works. there's a section about sqlite templates in the guide, but there are some concepts in it that will require you to read at least some of the rest of it. « previousnext » this tutorial was kindly donated to mozilla by appcoast. ...
Mozilla Documentation Roadmap - Archive of obsolete content
ding and posting to the newsgroups. another advantage is that discussions are archived and searchable through google groups. other and finally, a couple resources you should also keep in mind: other extensions. there are thousands of extensions out there, and you may strike luck and find one that does exactly what you need. be sure to look at the license the extension's code is released with before thinking about copying large sections of it. also, remember to give credit when it's due. mozilla's bugzilla repository. pretty much every code change done in firefox and mozilla projects is documented in this huge tracking database. but this also means that finding exactly what you need can be time-consuming, and often fruitless. the advanced search is very useful in filtering results, but it i...
Observer Notifications - Archive of obsolete content
owseroverlay.uninit(); }, false); in the observe method the notification topic is verified because you can have one observer listening to several topics. you may notice that we explicitly set the interface of the asubject object to nsisupportsstring using the queryinterface method. this is because the first parameter of the observe method is typed as nsisupports (the generic interface, as seen before), therefore its properties and methods cannot be accessed unless the correct interface is set to it. when the notifytest method is called, all observers registered with xulschoolhello-test-topic will get notified and display two alerts. if there are 2 firefox windows open, the observer will be notified in both and the alerts will show up on both. you can always listen for multiple notification ...
Setting Up a Development Environment - Archive of obsolete content
this extension has seen little maintenance in quite some time, so it is very buggy. it is specially unreliable when debugging code in javascript xpcom and xbl files. nevertheless, it is a valuable tool when trying to figure out why a certain function is misbehaving. tamper data tamper data intercepts http requests and their responses. it allows you to cancel them and even replace payload data before it is sent. there are several similar extensions, such as live http headers, but tamper data is the one that we use the most. we'll cover more on http debugging later on. firebug the firebug extension includes pretty much all tools mentioned so far, but it's mostly focused on web development. the chromebug extension helps in making firebug more useful for extension development, but it may still...
The Box Model - Archive of obsolete content
changing the background color of the toolbars and status bars, font styles, sizes, etc. note that this is not really what you would expect from an extension, it's more like a theme. however, it's very interesting and useful to see how you can manipulate the appearance of firefox so easily. if you're not familiar with css, you should read this css getting started guide and other online resources before continuing with this tutorial. « previousnext » this tutorial was kindly donated to mozilla by appcoast. ...
XPCOM Objects - Archive of obsolete content
t float boolean boolean, prbool void void timestamps prtime this type is used to pass timestamps measured in milliseconds, such as the output of the gettime() method in a javascript date object. there are more details about xpidl in the xpdil syntax definition. creating your own components javascript xpcom components as we've said before, we recommend using jsm whenever you can. yet there are some cases where you don't have a choice and you have to create xpcom components to add a specific feature. in these cases you can choose between compiled xpcom components, written in c++, or js xpcom components. you should favor the latter, they are much less complicated to make and maintain. most of the time you'll need 2 source files for...
Signing an XPI - Archive of obsolete content
: create a test certificate create a test certificate, using the -p option to set a password for the new certificate c:\projects\codesigning\> signtool -g mytestcert -d . -p"password" using certificate directory: . warning: performing this operation while the browser is running could cause corruption of your security databases. if the browser is currently running, you should exit the browser before continuing this operation. enter "y" to continue, or anything else to abort: y enter certificate information. all fields are optional. acceptable characters are numbers, letters, spaces, and apostrophes. certificate common name: xpi test organization: tjworld organization unit: software state or province: nottingham country (must be exactly 2 characters): gb username: tj email address: certifi...
Supporting search suggestions in search plugins - Archive of obsolete content
...
Tabbed browser - Archive of obsolete content
r window or running too early. you can access gbrowser only after the browser window is fully loaded. if you need to do something with gbrowser right after the window is opened, listen for the load event and use gbrowser in the event listener. if your code does not have access to the main window because it is run in a sidebar or dialog, you first need to get access to the browser window you need before you can use gbrowser. you can find more information on getting access to the browser window in working with windows in chrome code. from a sidebar basically, if your extension code is a sidebar you can use: var mainwindow = window.queryinterface(components.interfaces.nsiinterfacerequestor) .getinterface(components.interfaces.nsiwebnavigation) .quer...
Adding preferences to an extension - Archive of obsolete content
« previousnext » 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 of the ones included in the popup menu. as before, concepts covered in the previous articles in this series won't be rehashed here, so if you haven't already seen them: creating a status bar extension creating a dynamic status bar extension also, for reference, you may want to take a look at preferences system and the preferences api. download the sample you can download a copy of this sample to look over, or to use as the basis for your own extension. get the code here: download the sample update the m...
Creating a status bar extension - Archive of obsolete content
:maxversion>2.0.0.*</em:maxversion> </description> </em:targetapplication> </description> </rdf> let's take a look at some key parts of the manifest. extension identification information certain information is needed so firefox can uniquely identify your extension. in this sample, these fields are: property name description id a unique identification string. before firefox 1.5, this was a guid. starting with firefox 1.5, however, you should use a string in the form extension-name@creator-domain. version the extension's version number. type the addon type. for extensions, this is 2. human-readable information in this sample, we have four pieces of human-readable information; that is, information that is displayed to the user wit...
Events - Archive of obsolete content
archived event pages domsubtreemodifiedmozaudioavailablemozbeforeresizemozorientationcachedchargingchangechargingtimechangecheckingdischargingtimechangedownloadingerrorlevelchangenoupdateobsoleteprogressupdateready ...
Inner-browsing extending the browser navigation paradigm - Archive of obsolete content
ces like xmlhttprequest (currently offered in netscape 7 and internet explorer 6). data bind: mutation in the current document this step takes care of applying the changes into the current document, based on the data loaded, and uses dom interfaces. the mechanism can be as simple as copying new content to the current document, or as complex as performing dynamic transformations on the data source before applying the changes into the current document. for example, if a given web site's framework uses xslt to format xml contents as html, would be appropriate to reuse xslt to format new data that is about to be part of the current document. the next section illustrates a case of implementation using javascript, iframes and dom. inner-browsing with iframes and javascript a very simple way to approac...
JXON - Archive of obsolete content
ements, as is common with many xml dialects (including of course xhtml). the ecmascript standard (javascript) indicates that object iteration order is implementation dependent. appendix: a complete, bidirectional, jxon library now we can create a more complete, bidirectional, jxon library based on all our algorithms (see: #1, #2, #3, #4, reverse). its usage is modeled on the json native object. before implementing it in a working environment, please read the note about the const statement compatibility. the following code is also available on github. "use strict"; /*\ |*| |*| jxon framework - copyleft 2011 by mozilla developer network |*| |*| revision #3 - october 31th, 2016 |*| |*| https://developer.mozilla.org/docs/jxon |*| https://developer.mozilla.org/user:fusionchess |*| https://gi...
Images, Tables, and Mysterious Gaps - Archive of obsolete content
bout that in a bit-- but almost nobody ever changes the value from its default. let's take away the text, and leave only the image, as was done in figure 5. so we have an image sitting on the baseline of a line box that contains only the image. now consider what happens when we put that line in a table cell (figure 6). and there you have it-- spaces opening up where none have ever been seen before. it gets even worse with small images, like ones 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 d...
Installing plugins to Gecko embedding browsers on Windows - Archive of obsolete content
sers raises the scenario of more than one gecko-based browser that a netscape-style plugin can work with, it becomes important to let plugin developers know how to discover these browsers on a windows machine. this information applies to mozilla based browsers that pull the mozilla codebase after the mozilla 0.9.1 milestone release. none of the registry keys mentioned here are written by browsers before the mozilla 0.9.1 timeframe. for example, netscape 6.0 and 6.01 do not write any of these keys into the registry, and thus these keys are not available for plugin vendors to parse for these two browsers. netscape 6.1 and onwards, however, will write these keys, and so creating a plugin installer that puts the shared object (dll) in the right place becomes much easier, since the relevant meta-info...
Source Navigator - Archive of obsolete content
in a terminal window: sudo apt-get install sourcenav this should install source-navigator. one can check whether the installation is complete by executing: $ which snavigator /usr/bin/snavigator importing the source execute the following: snavigator. this triggers a splash screen, followed by a "source-navigator projects" dialog as the following: i've already created a new project bin.proj before documenting this. if this is your first time to open source navigator, the big white box on the left of the dialog should contain no lines. click "new project". this shows the "auto-create project" dialog: which allows you to decide your filename of the project file (which ends in .proj) and your source directory/directories that you want to import into the project. (you can always include more ...
Visualizing an audio spectrum - Archive of obsolete content
s there */ signal = new float32array(fb.length / channels), magnitude; for (var i = 0, fbl = framebufferlength / 2; i < fbl; i++ ) { // assuming interlaced stereo channels, // need to split and merge into a stero-mix mono signal signal[i] = (fb[2*i] + fb[2*i+1]) / 2; } fft.forward(signal); // clear the canvas before drawing spectrum ctx.clearrect(0,0, canvas.width, canvas.height); for (var i = 0; i < fft.spectrum.length; i++ ) { // multiply spectrum by a zoom value magnitude = fft.spectrum[i] * 4000; // draw rectangle bars for each frequency bin ctx.fillrect(i * 4, canvas.height, 3, -magnitude); } } var audio = document.getelement...
Automated testing tips and tricks - Archive of obsolete content
o add a profile entry to profiles.ini and populate the new profile directory with a prefs.js file firefox-bin -createprofile "testprofile ${profile_dir}/testprofile" next, start firefox to populate the new profile directory with the rest of the default settings firefox-bin -p testprofile -chrome chrome://tests/content/quit.xul<code> the above process may exit before the profile is completely created. in test scripts, <code>sleep 5 after the above command should ensure the profile is created before the next command in the test script is run how to enable dump in a new profile add user_pref("browser.dom.window.dump.enabled", true); to profiledir/user.js how to execute test code with chrome privileges using a chrome doc - see sb...
Other Mozilla customization pages - Archive of obsolete content
other mozilla customization pages mcd, mission control desktop aka autoconfig pre-configuring mozilla mozexec, a mozilla launcher that writes a registry.bat before launching mozilla (contributed by petr kristan) mozptch: the main difference of the mozptch approach is, not to patch the registry.dat, but to create a new one with mozillas comandline option -createprofile. at the moment all messages of the program are in german language. this because the program was developped for mozilla configuration in a german administration with about 2000 users. ...
Protecting Mozilla's registry.dat file - Archive of obsolete content
me, and this seems to have the interesting "side-effect" of wiping any non-microsoft subfolders from %userprofile%\application data, including mozilla's . in order to prevent this, it's preferable to have mozilla's registry.dat file copied over from the server using the logon script. moreover, it's advisable to "protect" the mozilla registry using attrib +r +s in case the logon script is finished before ie's "personnalized settings" have completed their dirty deed... in summary, you can use the following series of commands in your logon script (usually stored in /home/samba/netlogon/startup.bat on the server): rem ================================================== rem mozilla rem ================================================== attrib -r -s "%userprofile%\application data\mozilla" >nul 2>nul ...
Bookmark Keywords - Archive of obsolete content
as been bookmarked, we need only adjust the boookmark's properties. in this case, we'll give it a keyword and title of google and replace the term "geitost" with the %s, as shown (with extra highlighting) in figure 8. now we can run google searches straight from the address bar. these searches can be as complex as google will tolerate, since the entered data will be converted to url-encoded text before it's sent to the google servers. thus we could type any of the following into the address bar and get back useful results: <tt>google geitost</tt> <tt>google mozilla keyword bookmark</tt> <tt>google bookmark site:developer.netscape.com</tt> <tt>google netscape xml support -site:netscape.com</tt> a few examples in the course of writing this article, a number of potentially useful bookmarks...
Enabling the behavior - updating the status bar panel - Archive of obsolete content
he build failed tests. the color green ("11dd11") means the client successfully built and tested mozilla. when it finds a color, it sets the panel's status attribute to the corresponding status, which causes the previously defined css rules to switch to the icon appropriate for that status. because our conditional looks for worse states (bustage, test failures) first, it will display those states before displaying the success state. « previousnext » ...
Making a Mozilla installation modifiable - Archive of obsolete content
e files in the archive and see our changes to the ui merely by restarting the application. this makes modifying mozilla's ui much easier than for many other applications. although mozilla stores the ui files in jar archives, it can also access them in their original, unarchived form, which is useful for the extensions developer because it makes it unnecessary to extract the files from the archive before changing the code and then re-add them to the archive afterwards. instead, you only have to extract them once and can then make as many modifications as you like. to make mozilla modifiable, we will first extract the ui files from the archives using an unzip utility, then edit mozilla's registry of ui files to use the extracted files instead of the original jar archives. the archives are stored w...
Making it into a dynamic overlay and packaging it up for distribution - Archive of obsolete content
nderstatus/content/tinderstatus.css" type="text/css"?> <overlay id="tinderstatusoverlay" xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> <script type="application/javascript" src="chrome://tinderstatus/content/tinderstatus.js" /> <statusbar id="status-bar"> <statusbarpanel class="statusbarpanel-iconic" id="tinderbox-status" insertbefore="offline-status" status="none"/> </statusbar> </overlay> we also need to change the urls in the copy of tinderstatus.css: statusbarpanel#tinderbox-status { list-style-image: url("chrome://tinderstatus/content/tb-nostatus.png"); } statusbarpanel#tinderbox-status[status="success"] { list-style-image: url("chrome://tinderstatus/content/tb-success.png"); } statusbarpanel#tinderbox...
Tinderbox - Archive of obsolete content
sly build and test mozilla and report their results back to a server that makes those results available via a web page. the tool enables mozilla.org to be immediately notified of changes to the code that prevent mozilla from compiling and running (or compromise performance and footprint) so they can get someone to fix the problem or reverse the changes. mozilla engineers regularly check tinderbox before changing the code because changes are prohibited while the codebase is broken. the mozilla sheriff, a rotating position responsible for watching the code and getting engineers to fix breakage, checks tinderbox even more regularly. while it isn't difficult to load the tinderbox web page or sidebar, it would be useful to have an even quicker way to check tinderbox that doesn't require going to a we...
Installing Dehydra - Archive of obsolete content
ewer branches (like aurora_base_20120131) are working, too. please also note that autoconf v2.13 is really needed: it does not work with e.g. v2.68. there is no need for some installation after make. you can skip the next section "building gcc 4.5" if you are using gcc 4.6 or above. building gcc 4.5 for treehydra's process_tree_decl to work, when compiling with g++, you must use a patched gcc 4.5 before building dehydra. cd $home # obtain gcc 4.5.3 (see http://gcc.gnu.org/mirrors.html for alternate mirrors) wget http://www.netgull.com/gcc/releases/gcc-4.5.3/gcc-4.5.3.tar.bz2 tar -jxvf gcc-4.5.3.tar.bz2 # apply plugin_finish_decl patch wget https://bug559964.bugzilla.mozilla.o....cgi?id=457606 -o finish_decl.diff cd gcc-4.5.3 patch -p0 < ../finish_decl.diff # build gcc cd .. mkdir gcc-objdir mk...
Download Manager preferences - Archive of obsolete content
e firefox is run; 1 indicates that the downloads should be paused but will not automatically resume when the application is restarted; and 2 indicates that the downloads will be canceled on quit. default value is 0 (resume on next launch). browser.download.manager.resumeonwakedelay an integer value indicating the number of milliseconds to wait after the system wakes up from sleep before resuming downloads. default value is 10000. browser.download.manager.retention indicates how long downloads are retained in the download manager's queue after the download is completed successfully. 0 indicates that the download should be removed upon completion; 1 indicates that completed and canceled downloads should be removed on quit; 2 indicates that downloads should never be re...
Error Console - Archive of obsolete content
m the tools menu or by ctrl-shift-j. for information about what javascript exceptions get logged into the error console, and how to make all exceptions get logged, read the article exception logging in javascript. see setting up extension development environment#development preferences for the preferences you should set if you want to see errors from firefox and extensions in the error console. before gecko 1.8.1 (firefox 2), it was called javascript console (see bug 265871). types of errors error usually a syntax error that prevents the program from compiling. warning usually lets the program compile but warns of bad coding and suggests design flaws. message very similar to warning, used very rarely. manipulating data displayed in e...
Extension Frequently Asked Questions - Archive of obsolete content
find the extension howto or faq pages helpful. if you're looking for a place to get started, try our tutorial, building an extension or mozillazine's getting started tutorial. use the extension wizard to generate a template to start with. be sure to set the development preferences. todo: add content. where can i get more help? please see extensions:other resources and extensions:community. before asking for help, be sure to set the debugging prefs and check the error console for related messages. also, don't forget to do at least a simple web search before asking. and read this faq! ...
Documentation for BiDi Mozilla - Archive of obsolete content
layout code has to reverse text fragments or to allow for the fact that they are displayed in reverse. in general, this happens whenever we are dealing with less than a whole frame. examples of this are in nstextframe::painttextslowly; nstextframe::paintunicodetext when a selection is displayed; nstextframe::getposition; nstextframe::getpointfromoffset. text in visual mode must also be reversed before display on a bidi platform. text fields and composer the specification of the bidi changes to composer was posted in the editor and i18n newsgroups, and responses there were taken into account. the implementation is mostly in layout code, especially in nsselection.cpp and nscaret.cpp. other bidi functionality clipboard: based on bidi options in preferences, the text mode of the clipboard may b...
Layout FAQ - Archive of obsolete content
heck the dirty and dirty_children framestate flags. that won't help with pending style changes, but it'll work to detect cases when the popup or something in it needs to be reflown. ...
Layout System Overview - Archive of obsolete content
straight-forward, but is complicated somewhat by the notion of incrementalism. one of the goals of the layout system's design is to create parts of the presentation as they become available, rather than waiting for the entire document to be read, parsed, and then presented. this is a major benefit for large documents because the user does not have to wait for the 200th page of text to be read in before the first page can be displayed - they can start reading something right away. so really, this sequence of operations resolve style, create frame, layout frame, gets repeated many times as the content becomes available. in the normal in-flow case this is quite natural because the sequential addition of new content results in sequential addition of new frames, and because everything is in-flow, th...
GRE - Archive of obsolete content
ee above). dynamically link to that gre using the xpcomgluestartup() function. see environment variables below. initialize xpcom and do your work; when finished, shut down xpcom. unlink xpcom with xpcomglueshutdown(). dependent libraries and environment variables the xulrunner gre is designed so that the embedder does not need to set any environment variables such as path or ld_library_path before calling xpcomgluestartup(), because it dynamically loads the correct dependent libraries. unfortunately, the mozilla suite-based gre is not as forgiving, especially on linux. embedders will need to set the ld_library_path environment variable and start a new process in order to embed a suite-based gre correctly. ...
JavaScript crypto - Archive of obsolete content
ring libraryfullpath, long cryptomechanismflags, long cipherflags); loads or removes a new pkcs #11 module. in the add case, the module will be placed in the nss secmod.db database and will be loaded automatically on application restart. in the delete case, the module is removed from the nss secmod.db. this function will issue a user prompt to confirm the operation before the add or delete actually occurs. parameters modulename name of the module. libraryfullpath the filename of the library prepended with its full path. cryptomechanismflags a bit vector indicating all cryptographic mechanisms should be turned on by default (see below). cipherflags a bit vector indicating all ssl or s/mime cipher functions supported by the module (see below). mechanism...
Java in Firefox Extensions - Archive of obsolete content
ent 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". the following approach is taken from the extension xquseme (note you must use the latest version, currently still in the sandbox, as prior versions only worked with liveconnect before java 6 update 11) which borrows some of the code of the java firefox extension in order to grant full privileges to java within a firefox extension, but it is easier to understand and doesn't require creation of a xpcom component. [note: a simpler hello world version than that below is now available at http://brett-zamir.me/java_demo/ ] for privileges, the basic procedure is: download and inclu...
Me - Archive of obsolete content
Archive › Mozilla › Jetpack › Meta › Me
note: this page documents the jetpack prototype, which is no longer under active development. read the experiment report for what we learned from it and the blog post announcing the first sdk release for what we're up to next! the jetpack.me namespace provides mechanisms for introspecting the dynamic state of your jetpack. the namespace currently lives in the future and must be imported before it is used: jetpack.future.import("me"); methods onfirstrun(funcfunction)jetpack.me.onfirstrun() allows jetpacks to be notified after they are successfully installed. onfirstrun() accepts a callback which is called after installation. note that this mechanism is independent of the first-run page; in particular, the callback is not a load event listener or jquery ready callback. onfirstrun() may be...
Settings - Archive of obsolete content
to specify user-configurable settings. 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. the value of the settings property is an array of objects representing the settings to expose to users. jetpack will automatically generat...
Settings - Archive of obsolete content
acks to specify user-configurable settings. 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: jetpack.future.import("storage.settings"); 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. the value of the settings property is an array of objects representing the settings to expose ...
Clipboard - Archive of obsolete content
hello world");// in other clipboard get(flavor string)returns data to jetpack from the clipboard. if flavor is provided, the data is returned in that format. flavorreturns data to jetpack from the clipboard. if flavor is provided, the data is returned in that format. string here's an example of how to use the method to get the data on the clipboard. remember to import clipboard from the future before calling it. jetpack.import.future("clipboard");var mycontent = "<i>this is some italic text</i>";jetpack.clipboard.set( mycontent, "html" ); getcurrentflavors()returns an array of available jetpack clipboard flavors, for the current system clipboard state. jetpack.import.future("clipboard");var mycontent = "<i>this is some italic text</i>";jetpack.clipboard.set( mycontent, "html" );var flavs = je...
Clipboard - Archive of obsolete content
ello world"); // in other clipboard get(flavor string)returns data to jetpack from the clipboard. if flavor is provided, the data is returned in that format. flavorreturns data to jetpack from the clipboard. if flavor is provided, the data is returned in that format. string here's an example of how to use the method to get the data on the clipboard. remember to import clipboard from the future before calling it. jetpack.import.future("clipboard"); var mycontent = "<i>this is some italic text</i>"; jetpack.clipboard.set( mycontent, "html" ); getcurrentflavors()returns an array of available jetpack clipboard flavors, for the current system clipboard state. jetpack.import.future("clipboard"); var mycontent = "<i>this is some italic text</i>"; jetpack.clipboard.set( mycontent, "html" ); var fl...
Clipboard - Archive of obsolete content
ello world"); // in other clipboard get(flavor string)returns data to jetpack from the clipboard. if flavor is provided, the data is returned in that format. flavorreturns data to jetpack from the clipboard. if flavor is provided, the data is returned in that format. string here's an example of how to use the method to get the data on the clipboard. remember to import clipboard from the future before calling it. jetpack.import.future("clipboard"); var mycontent = "<i>this is some italic text</i>"; jetpack.clipboard.set( mycontent, "html" ); getcurrentflavors()returns an array of available jetpack clipboard flavors, for the current system clipboard state. jetpack.import.future("clipboard"); var mycontent = "<i>this is some italic text</i>"; jetpack.clipboard.set( mycontent, "html" ); var fl...
Litmus tests - Archive of obsolete content
a "smoke test" is a quick check, done to verify the basic functionality of a certain feature, or a sanity check of the build process. ...
Monitoring downloads - Archive of obsolete content
s fetched and inserted into the appropriate list cell. the interesting bits to take away from this: mozistoragestatement has several data getter routines for fetching search results, including getstring(), getdouble(), and getint64(). these methods take as a parameter the zero-based index number of the column whose value you wish to retrieve. note that the start time is being divided by 1000 before we create a javascript date object from it. that's to adjust the value from the granularity stored in the database to that expected by javascript. to right-justify the numeric columns, we set the appropriate cells' style attribute to text-align:right. exercises for the reader there are some obvious things that could be done to improve this extension. if you're learning to use the download man...
Mozilla Application Framework in Detail - Archive of obsolete content
es and to accelerate the growth and development of the next-generation internet. small, fast and standards compliant, gecko is easily embeddable across platforms in browsers, desktop applications and browsing devices and delivers full-functionality browsing to them all. innovative gecko technologies it supports make the development of browsers, applications and devices faster and easier than ever before. gecko is the first browser engine ever to deliver the full web standards support that developers have been calling for. this robust standards support for the first time makes it possible to implement powerful web applications with rich user interfaces without using proprietary or platform dependent code. because gecko has a cross-platform architecture, is easily embeddable and is open source, it...
Mozilla Crypto FAQ - Archive of obsolete content
ance) released source code through mozilla.org for the personal security manager and network security services software; this source code included support for the ssl protocol, but due to the rsa patent and related legal issues it did not originally contain code for rsa or other cryptographic algorithms. on september 6, 2000, rsa security released the rsa patent into the public domain, two weeks before the patent was scheduled to expire (on september 20, 2000). shortly thereafter the nss developers began work on an open source implementation of the rsa algorithm; that code, together with code previously developed for other cryptographic algorithms, will be included in a new version 3.1 of the nss open source cryptographic and pki library. this new rsa-capable version of nss will then be includ...
LIR - Archive of obsolete content
addd double add double 101 subd double subtract double 102 muld double multiply double 103 divd double divide double 104 modd double modulo double lir_modd is just a place-holder opcode, ie. the back-ends cannot generate code for it.it's used in tracemonkey briefly but is always demoted to a lir_modl or converted to a function call before nanojit has to do anything serious with it. 105 cmovi integer conditional move int 106 cmovq quad 64 bit conditional move quad 107 cmovd double conditional move double conversions 108 i2q quad 64 bit sign-extend int to quad 109 ui2uq quad 64 bit zero-extend unsigned int to unsigned quad 110 q2i integer 64 bit truncate q...
Bundles - Archive of obsolete content
on linux and under ~/library on os x. since this folder maybe be located in a directory that requires elevated privileges, the web application should not write data to it. the application profile directory can be used instead for this purpose. note: the webapp must have an id in order to be installed. when prism is launched with a "-webapp [bundle]" command line, the bundle must first be unpacked before the web application is launched. this can slow the overall launch time and the unpacking is redundant if the bundle has been launched previously. this is why the preferred method of launching is to use the "-webapp [webapp-id]" command line, which looks for the previously installed (unpacked) web application in the prism webapps/{webapp-id} folder. the web application is then launched without the...
New Skin Notes - Archive of obsolete content
etc. oh, i went back to login page, logged in and then from there went to the /test/ pages and it's like the old look (with menu bar at the left), where indeed, the logout link is as it should be on the left in personal tools. --mmondor 12:49, 26 aug 2005 (pdt) the logout link is exactly where the login link is. this makes sense as-is. not changing. --dria the menu column seems larger than before in the current test theme, so as to cause some reference pages to look ugly when browser set in 800x* resolution, using the default firefox 1.0.6 fonts settings on xfree86. a few examples: , .these work fine with the old theme, and i expect that this affects a lot of reference articles. that our screen resolutions are now wider than 800 pixels width does not mean that we always want to enlarge th...
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. ...
Table Cellmap - Archive of obsolete content
(map) { if (map->getrowcount() > rowindex) { // add your action here } rowindex -= map->getrowcount(); map = map->getnextsibling(); } data entry the usual way to populate the cellmap is via nstableframe::insertrows. enabling the debug code at the function entrance and exit gives a quite complete picture of the cellmap structure. below follows the dump for the 2x2 table. ...
Table Layout Regression Tests - Archive of obsolete content
it has been, as the "rtest" testing framework described here has been superseded by the reftest framework. it is unclear whether or how well rtest continues to work and whether it is still used or not. subject overview changes in layout, parser and content code can have unintended side effects, also known as regressions. it is good style to check for these unwanted regressions and fixing them before checkin rather than causing bugzilla avalanches. prerequisites in order to run these tests, you will need to have: make sure that your build is a debug build (in short you need ac_add_options --enable-debug in your .mozconfig file). to build the layoutdebugger itself, build either all extensions or include layoutdebug in your .mozconfig file. for example ac_add_options --enable-extensions=a...
Tamarin Acceptance Testing - Archive of obsolete content
in order to ensure that changes to the tamarin code base are high quality before submitting, all developers are required to complete the following steps. successfully build release and debug versions of the shell with the debugger enabled [info] successfully run the following test suites: acceptance test suite [info] self tests [info] submit a sandbox build request to test against platforms that you may not have locally [info] available tamarin acceptance test suites actionscript acceptance tests: actionscript acceptance tests running tamarin acceptance tests abc assembler tests cmdline tests performance tests actionscript performance tests running tamarin performance tests built-in self tests ...
Tamarin build documentation - Archive of obsolete content
the windows mobile 6 sdk, you can build for windows mobile (arm) targets. apple xcode the project files are designed for xcode 3.0. see "platform/mac/avmplus/avmplus.xcodeproj/". xcode 2.2, 2.3, and 2.4 will not work. there are two targets in the xcode ide, 'avm' for 32-bit builds and 'avm64' for 64-bit builds. there is also an aggregate target that will build both targets. note that, whereas before when you selected the aggregate target you got a 'shell' 32-bit executable and a 'shell64' 64-bit executable in the same folder, now because of the fix to bug 478714 you will get an 'avm' executable in two separate folders, /debug and /debug64 respectively. the command to build from the terminal is: $ cd tamarin-redux $ xcodebuild archs=ppc -project platform/mac/avmshell/avmshell.xcodepro...
Tamarin Build System Documentation - Archive of obsolete content
s approximately 1 hour 45 minutes. the performance and deep phases do not run synchronously. the phases run when slaves are available and the other phases do not wait for completion to start the next build. how are builds triggered? checkins (hg push) to http://hg.mozilla.org/tamarin-redux and sandbox requests will trigger a buildbot build when all build slaves are idle the next build begins before the build begins buildbot waits for 2 minutes of no checkin activity the build system prioritizes tamarin-redux checkins over sandbox builds when several tamarin-redux checkins occur the newest change is built including all checkins since the last build each sandbox build occurs in the order they were submitted, the submitter may cancel a build. how do i build a sandbox build? create a user r...
The life of an HTML HTTP request - Archive of obsolete content
eam it gets via its streamlistener interface and converts it to nsiparsernodes which it places in the contentsink. the parser typically gets data from the stream in 8kb blocks and parses these blocks, block by block. after every parsed block it passes the parsed data as nsiparsernodes to the contentsink unless the parser has been temporarily blocked, in wich case it waits until it gets unblocked before parsing the cached data it has receieved while being blocked. (6) the contentsink then builds up nsicontent nodes that describe the document. these content nodes are created by calling functions like ns_newhtmlxxxxelement(). these element nodes implement the nsihtmlcontent interface as well as their respective dom interfaces. nsicontent::appendchild() is used to build the content tree but append...
Tuning Pageload - Archive of obsolete content
gs you should know. the data flows in gecko as follows: network -> necko -> parser -> content sink -> content model -> rendering model -> layout -> painting. nglayout.initialpaint.delay this is a preference that specifies a delay, in milliseconds, after the data from the server has started coming in. during this delay, the page that's coming in is not painted, unless it ends up fully loaded before the delay expires. the idea here is twofold.this reduces ugly visual jitter as the new page comes in by not starting painting till after we have a bunch of the data.this makes overall page load time shorter by not doing extra repaints very early on. content.interrupt.parsing this preference, when true, means that the content sink can tell the parser to stop for now and return to the event loop...
URIs and URLs - Archive of obsolete content
normally, the only time escape encodings can safely be made is when the uri is being created from its component parts; each component may have its own set of characters that are reserved, so only the mechanism responsible for generating or interpreting that component can determine whether or not escaping a character will change its semantics. likewise, a uri must be separated into its components before the escaped characters within those components can be safely decoded. this implies that the segments of urls are escaped differently. this is done by ns_escapeurl which is now part of xpcom, but started as part of necko. the information how to escape each segment is stored in a matrix. also a string should not be escaped more than once. necko will not escape an already escaped character unless fo...
Using gdb on wimpy computers - Archive of obsolete content
the debugger uses a lot of memory. how do i fix it? if your computer has less than 256 mb of memory, your computer will become unhappy as gdb loads mozilla's shared libraries. the solution to this is to delay loading shared libraries until they are actually needed. however, you need to make sure that the base libraries like libc and pthreads are loaded before you tell gdb to stop loading shared libraries. if you don't allow those libraries to be loaded then gdb will not be able to properly debug threads on linux. mozilla uses pthreads for its networking library so you need to be able to work in a threaded environment. the best way to do this is to set a breakpoint in main, let the program run until main and then turn off automatic library loading. from there you can allow the program to continu...
Venkman Internals - Archive of obsolete content
sdscript instead, you wouldn't see it in the venkman ui, and you might confuse venkman when the actual breakpoint was hit and it couldn't find a matching breakpoint object. you can see the prototype for this object at http://lxr.mozilla.org/mozilla/sourc...ebugger.js#914 scriptwrapper.jsdscript is the reference to the jsdiscript object for the function. sourcecontext is the 5 lines of source text before the last instance of the word "function" on the line where this function starts. (not in 2006, seems to be computed on the fly in getsourcecontext()). the full text of the file can be found in an array located at scriptwrapper.scriptinstance.sourcetext.lines. this array is 0 based, of course. the starting line of the function is scriptwrapper.jsdscript.baselinenumber (one based). the total length...
Venkman Introduction - Archive of obsolete content
h javascript it executes as the browser opens web pages, it's usually enough simply to browse the sites whose scripts you are interested in debugging. debugging basics this section provides a brief example of a debugging session in order to familiarize you with some of the basic commands and operations of the debugger. start venkman note: at one point, the debugger needed to be started before the scripts it was going to debug. this limitation is fixed, and now the javascript compiler makes all the scripts you access via the browser available to the debugger. see loading scripts into the debugger for more information about finding and loading scripts in venkman. launch a browser window and go to http://wp.netscape.com/fishcam/dhtmltank.html. note that in mozilla 1.x and netsca...
Using Breakpoints in Venkman - Archive of obsolete content
et a future breakpoint. except for this distinction, breakpoints in venkman work like breakpoints in most other debuggers. the dots you see in the left margin of the source code view indicate which lines contain executable code, places where a hard breakpoint can be set. setting breakpoints clicking on one of these dots in the source code view will set a breapoint at that line. venkman will stop before the line executes. when a breakpoint is set, the margin will change to the letter "b", as in figure 2. if you execute this code again after having set this breakpoint, venkman will stop at line 81. (note: by default, venkman hides files file that appear to be part of the browser core; this includes extensions. to debug an extension, uncheck "exclude browser files" on the debug menu and your insta...
Writing textual data - Archive of obsolete content
00: os.init(fos, charset, 0, "?".charcodeat(0)); you can, of course, replace the "?" in that example with any other character. you can also specify any unicode character u+abcd directly as 0xabcd. note: if the replacement character is not a supported character in the chosen character encoding, attempts to write unsupported characters will fail with ns_error_loss_of_significant_data. versions before gecko 1.8 firefox 1.0.x, mozilla 1.7.x and older versions do not support nsiconverteroutputstream. alternative ways usable from javascript do not support character encodings that use embedded nulls (such as utf-16 and utf-32). they work by manually converting the string you want to write to a byte sequence using nsiscriptableunicodeconverter, and writing that to the stream. here's an example: ...
Binding Implementations - Archive of obsolete content
w values, an initial value can be specified as a child of the property tag. the script is evaluated at the time of binding attachment and the resulting value is stored on the element. it can be assumed that the anonymous content of the binding has been fully constructed, although the bindingattached event will not have fired. property initialization always takes place after content generation but before the firing of a binding attachment event, since the bindingattached handler needs to be able to assume that all properties will be accessible on the binding. properties with getters and setters can define them using onget and onset attributes, or using the more verbose getter and setter elements. if both the attribute form and the element form are used to specify a getter or setter, then the ele...
Example Sticky Notes - Archive of obsolete content
parsing as the engine doesn't go through cdata sections but simply skip on them. --> <constructor><![cdata[ /** * the code below will be called one time only after * the binding is successfully prepared and bound. * "this" in this context refers to the bound element. */ // your code goes here ]]></constructor> <destructor><![cdata[ /** * the code below will be called one time only before * binding is unbound. you cannot cancel this event, * but you may accomplish some last minute clean up. * "this" in this context refers to the bound element. */ // your code goes here ]]></destructor> <field name="priority"><![cdata[ /** * new "real" property for the bound element. * within this block the content is interpreted * as javascript code. the result of this code * evaluat...
Using XPInstall to Install Plugins - Archive of obsolete content
efreshed by correctly invoking the refreshplugins api. by refreshing your plugin, you're ensuring that the plugin is available for use immediately, without obliging the user to restart their browser. this is one of the chief advantages of a smooth xpinstall experience. the first install problem the first install problem refers to the conditions arising when a plugin arrives on a user's machine before a browser arrives. the recommended install process addresses this issue, which is to install to a secondary location after installing to the current browser. in a nutshell, the first install problem can be summed up by the question: how can a browser which is installed on a user's machine after a given plugin has already been installed by the user benefit from the existing installation rather tha...
addFile - Archive of obsolete content
the performinstall method after you've successfully added all files. note: if you are installing binary files on a macintosh, be aware that the binary format for those files must be applesingle if the resource information is to be installed properly. some file transfer programs will convert apple binaries to this format on transfer if you transfer them from a macintosh to a unix/windows machine before zipping up those files on that target system. example var xpisrc = "file.txt"; initinstall("adding a file", "addfile", "1.0.1.7", 1); f = getfolder("program"); setpackagefolder(f); addfile(xpisrc); if (0 == getlasterror()) performinstall(); else cancelinstall(); ...
initInstall - Archive of obsolete content
ch as "1.17.1999.1517". flags an optional field; reserved for future use. pass 0 as the default value. returns an integer error code. for a list of possible values, see return codes. description the initinstall method initializes the installation of the specified software. you must call this method immediately after the constructor. it is an error to call any other install methods before calling initinstall. after calling initinstall, your script must call performinstall or cancelinstall before it finishes. if your script does not call performinstall or cancelinstall, netscape 6 will not be able to clean up properly after your script finishes. example to start installation for the royal airways plug-in, you could use this code: initinstall("royal airways tripplanner","/royalair...
createKey - Archive of obsolete content
ator\\mail". classname usually an empty string. for information on this parameter, see the description of regcreatekeyex in your windows api documentation. returns 0 if it succeeded; a nonzero number if it failed to schedule the creation. for a list of possible values, see return codes. description the createkey method adds a key to the registry. you must add a key to the registry before you can add a value for that key. ...
Learn XPI Installer Scripting by Example - Archive of obsolete content
to the method. initializing the installation all installations must begin with initinstall(). the initinstall() method on the install object creates a new installation for the specified software and version. in the browser.xpi installation, this function appears at line 20: var err = initinstall("netscape seamonkey", "browser", "6.0.0.2000110807"); if you call a method on the install object before initinstall(), you will get an error. the initinstall method takes the following parameters: the display name of the package, the name of the package as it appears in the client registry, and the version, which can be expressed as a number or as an installversion object. in the example above, "netscape seamonkey" is the display name, "browser" is the registry name, and the version is "6.0.0.2000...
norestorefocus - Archive of obsolete content
if true, the focus will not be reset, although it will be cleared if the focus is within the panel. ...
accesskey - Archive of obsolete content
same as its accesskey, the first of those characters in the label will be underlined. if a label doesn't have the specified character, the character will be appended to the label with parentheses. for example, when an accesskey of an 'open' label is 'a', the generated label will be 'open (a)'. however, if the last character of the label is an ellipsis or a colon, the accesskey text is inserted before them. this allows a label of 'open…' with an accesskey of 'a', to have a generated label of 'open (a)…'. similarly, when the label is 'your name:' and the accesskey is 'b', the generated label will be 'your name (b):'. it is recommended that you only use characters that appear in the label. however in some languages, for example, in japanese, characters will not always map directly to singl...
browser.type - Archive of obsolete content
ontent type. this boundary has a number of special effects, such as making window.top == window (unless the browser is added to a chrome document), and preventing documents from inheriting the principal of the parent document. the type attribute on all frames in content documents is ignored; subdocuments of content documents are always content documents. warning: the type attribute must be set before the element is inserted into the document. content a browser for content. the content that is loaded inside the browser is not allowed to access the chrome above it. content-primary the primary browser for content. the content that is loaded inside the browser is not allowed to access the chrome above it. for instance, in a web browser, this would be the element that displays the we...
insertafter - Archive of obsolete content
this value may be a comma-separated list of ids, which are scanned and the first one found in the window is used. ...
onpopupshowing - Archive of obsolete content
this handler is usually used to dynamically set the contents when the user requests to display it. ...
persist - Archive of obsolete content
...
popup.position - Archive of obsolete content
second word). the anchor value (ie, the first word) can be one of topleft, topright, bottomleft, bottomright, leftcenter, rightcenter, topcenter or bottomcenter. the popup value (ie, the second word) can be one of topleft, topright, bottomleft or bottomright. positions specified as a single word string are shortcuts for the values above. valid single-word values are after_start, after_end, before_start, before_end, end_after, end_before, start_after, start_before, overlap, at_pointer or after_pointer. for more details, including examples, please see popup positioning see also position ...
position - Archive of obsolete content
...
resizeafter - Archive of obsolete content
ight or below the splitter resizes. ...
state - Archive of obsolete content
« xul reference home state type: one of the values below indicates whether the splitter has collapsed content or not. this attribute will be updated automatically as the splitter is moved, and is generally used in a stylesheet to apply a different appearance for each state. open the content either before or after the splitter, depending on the value of the collapsed attribute, is currently displayed. collapsed the content either before or after the splitter is collapsed and is not visible. dragging the user is current adjusting the position of the splitter, typically by dragging it with the mouse. more info on splitters in the xul tutorial ...
treecol.type - Archive of obsolete content
rs. this is used in mozilla's download manager window. text the content of the columns is text. if you are using type="checkbox", then the tree and each treecol must be editable. you need to apply css to make the checkbox toggle. here is an example css style using the current theme's checkboxes: treechildren::-moz-tree-checkbox { /* unchecked checkbox treecells. this style must come before treechildren::-moz-tree-checkbox(checked) otherwise it won't take effect. */ list-style-image: none; } treechildren::-moz-tree-checkbox(checked) { /* checked checkbox treecells. cbox-check.gif isn't available in firefox 1, 2, and 3 in mac os x so you should specify a url to an image in your extension or elsewhere. */ list-style-image: url("chrome://global/skin/checkbox/cbox-check.
Deprecated and defunct markup - Archive of obsolete content
tabbox and tabpanel) <text> (like <label> or <description> but does not wrap; like <label crop="end">; had been used in menus/toolbars) <textfield> (like <textbox>) <thumb> (<button> with deprecated <gripper>; implements sliding box in center of scrolbar) <title> (to add a caption on a <titledbox> <titledbox> (box with a frame) <titledbutton> (attempt to combine text and images before <button>) <toolbarpaletteitem> required to embed non-buttons in customisable toolbars --neil 03 march 2011 <treebody> (old/experimental and unsupported xul tags) lives on as the internal name for the ancestor <treechildren> element --neil 03 march 2011 <treecaption> (old/experimental and unsupported xul tags) <treecolgroup> (former name for <treecols> <treecolpicker> (internal use ...
Reading from Files - Archive of obsolete content
t using nsiscriptableio.getfile(). in this case, the file 'sample.txt' within the user's home directory is retrieved. next, nsiscriptableio.newinputstream() is called to create a new input stream for reading from the file. this method will open the file and return a stream. naturally, if the file does not exist, an error will occur. you may wish to use nsifile.exists() to check if the file exists before opening it. in fact, it is a good idea to enclose file reading and writing operations within a try-catch block to capture any errors that might occur during the process. see file errors for a list of errors that might occur. the newinputstream method takes two arguments in this example. the first argument is the file to read from, and the second is a set of flags which control the reading. in thi...
Writing to Files - Archive of obsolete content
in either case, if the file already exists, it will be truncated to zero length. notruncate if used, don't truncate an existing file when opening it for writing. instead, just overwrite the existing content. if the new data being written is shorter than the existing data, the existing data will remain in the areas where no new data was written. if this flag is not used, the file is truncated before being written to. the flags are designed such that the most common case that is needed is with no flags set, so usually you will not set these flags. however, here is an example of how they might be used: var stream = io.newoutputstream(file, "text nocreate append"); the flags are specified in a space separated list as the second argument to the newoutputstream method. in this example, the nocr...
Moving, Copying and Deleting Files - Archive of obsolete content
ng a file within the same directory. when moving a file within the same directory, the destination argument may be null. for instance, the following example renames a file within the same directory: file.moveto(null, "hello.txt"); if the destination file already exists, nsifile.moveto() replaces the existing file. for this reason, you may wish to check if the file exists using nsifile.exists() before moving the file. deleting a file to delete a file, use nsifile.remove(). this method takes one boolean argument which indicates whether to delete recursively or not. if true and the file object refers to a directory, the directory will be removed as well all files and subdirectories within it. if false, a directory will only be removed if it is empty. if the directory is not empty, an error wil...
open - Archive of obsolete content
Archive › Mozilla › XUL › Method › Open
...
startFind - Archive of obsolete content
on's "find" command. this opens the findbar, focuses the edit field for the search term, and selects its contents. the first time this is called for a given findbar, the findbar will flash to draw attention to itself. the mode should be one of find_normal, find_typeahead, or find_links. if you don't pass a mode, the last-used mode for the same findbar is used. if the findbar hasn't been used before, find_normal is the default. example typically, you'll simply bind this method to your "find" command, like this: <command name="cmd_find" oncommand="gfindbar.startfind(gfindbar.find_normal);"/> ...
advance - Archive of obsolete content
Archive › Mozilla › XUL › Method › advance
« xul reference home advance( pageid ) return type: no return value call this method to go to the next page. this is equivalent to pressing the next button. the canadvance property must be set to true for the page to be changed. the code in the onwizardnext attribute is called before the page is changed. the pageid argument allows you to specify the index of the page to which to jump. supply null as the argument to go to the next page in the sequence. ...
cancel - Archive of obsolete content
Archive › Mozilla › XUL › Method › cancel
...
clearSelection - Archive of obsolete content
...
getPreviousItem - Archive of obsolete content
« xul reference home getpreviousitem( startitem, delta ) return type: element this method returns the item a given distance (delta) before the specified startitem, or null if no such item exists. this example will return the item five rows before someitem: getpreviousitem ( someitem, 5 ); ...
openPopup - Archive of obsolete content
supply an anchor node and set the position to a string indicating the manner in which the popup should be anchored. the anchor node does not need to be in the same document as the popup. unanchored popups may be created by supplying null as the anchor node. the direction in which the popup is oriented depends on the direction of the anchor. position possible values for position are: before_start, before_end, after_start, after_end, start_before, start_after, end_before, end_after, overlap, and after_pointer. check positioning of the popup guide for a precise description of the effect of the different values. x, y for an anchored popup, the x and y arguments may be used to offset the popup from its anchored position by some number, measured in css pixels. an unanchored...
replaceGroup - Archive of obsolete content
you can use the removetab method to remove the existing tabs first if that is desired. 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. ...
rewind - Archive of obsolete content
Archive › Mozilla › XUL › Method › rewind
...
Methods - Archive of obsolete content
hevent dom:element.getattribute dom:element.getattributenode dom:element.getattributenodens dom:element.getattributens dom:element.getelementsbytagname dom:element.getelementsbytagnamens dom:element.getfeature fixme: brokenlink dom:element.getuserdata dom:element.hasattribute dom:element.hasattributens dom:element.hasattributes dom:element.haschildnodes dom:element.insertbefore dom:element.isequalnode dom:element.issamenode dom:element.issupported dom:element.lookupnamespaceuri dom:element.lookupprefix dom:element.normalize dom:element.removeattribute dom:element.removeattributenode dom:element.removeattributens dom:element.removechild dom:element.removeeventlistener dom:element.replacechild dom:element.setattribute dom:element.setattributeno...
Namespaces - Archive of obsolete content
t has a "default namespace", and this is used with xul elements all the time. in xul documents, you'll usually see this: <window id="foo" xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> ... ... </window> and in xhtml documents, you'll see this: <html xmlns="http://www.w3.org/1999/xhtml"> ... ... </html> there is a very subtle difference here than before. before i wrote xmlns:xul="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul" but here the :xul piece is omitted. this signifies to the xml parser that http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul is the default namespace for the element and its descendant elements (unless further overridden by a default namespace on a descendant element), and that any element without...
Node - Archive of obsolete content
Archive › Mozilla › XUL › Node
3 short cdata_section_node 4 short entity_reference_node 5 short entity_node 6 short processing_instruction_node 7 short comment_node 8 short document_node 9 short document_type_node 10 short document_fragment_node 11 short notation_node 12 methods node appendchild ( node newchild ) node clonenode ( boolean deep ) boolean hasattributes ( ) boolean haschildnodes ( ) node insertbefore ( node newchild , node refchild ) boolean issupported ( string feature , string version ) void normalize ( ) node removechild ( node oldchild ) node replacechild ( node newchild , node oldchild ) ...
MenuItems - Archive of obsolete content
checked attribute set to the value true. the second menuitem is not checked by default. when the user activates the menuitem, the command event gets fired. from within a command listener, you can execute code which will change the state of the toolbar or status bar or whatever it is that need changing. you do not need to update the checked attribute as the menuitem will update this automatically before the command event is fired. note that the checked state is updated before the command event fires, so if you use the menuitem's checked attribute within the command listener, it will already be in the new state. <script> function changetoolbarstate(event) { if (event.target.getattribute("checked") == "true") showtoolbar(); else hidetoolbar(); } </script> ... <menuitem label="show to...
MenuModification - Archive of obsolete content
of the menu, the insertitemat method may be used in a similar fashion to insert an item into the menu elsewhere. menu.insertitemat(0, "delete", "delete"); in this example, the insertitemat method is used to insert a new 'delete' item at the beginning of the menu's popup. the first argument is the index where the new item should be inserted. in this case, 0 is supplied as the index, which means before the first item. indicies are counted starting at 0, so to insert an item before the fourth item pass 3 as the argument. the second and third arguments to insertitemat are the label and value for the new item, as with appenditem. both the appenditem and insertitemat methods return the new menuitem, so you can further modify it, for instance to add an access key, as in the following example: var ...
OpenClose - Archive of obsolete content
n, the openpopup method applies to the menupopup element. the anchor of a popup is the element node that the popup is displayed next to. for instance, to have a popup appear next to a button, pass a reference to this button as the first argument to the openpopup method. in this next example, the popup is opened relative to the document element. somepopup.openpopup(document.documentelement, "end_before", 0, 0, false, false); the second argument to openpopup is the anchor position, which specifies which side of the anchor the popup is positioned on. for instance, the value 'end_before' as used in the above example, indicates to place the left edge of the popup along the right edge of the the anchor element, aligned along the top edge of both. this may be confusing to understand, so see positio...
Panels - Archive of obsolete content
noautofocus attribute to true: <panel noautofocus="true"> this will cause the focus to remain on the element within the main window that has focus when the panel is opened. note that this will also keep the focus within the panel when it is closed. when a panel is closed, the focus is removed from the element within the panel which has the focus event, if any, and whatever element was focused before the panel was opened is refocused. you can prevent the focus from being removed by setting the noautofocus attribute to true as above. in addition, the norestorefocus attribute should be set to true in order to prevent the previously focused element from being refocused. normally, only the latter would be set if needed. this process of removing the focus when opening and closing a popup occurs a...
Special per-platform menu considerations - Archive of obsolete content
for the menu items that need to be placed on the application menu. on the mac, these menu items will be moved onto the application menu, but on other platforms, they will be left in their original locations. this makes it easier to write the same xul code for all platforms. here is a list of the menu item ids which are automatically handled. menu_filequitseparator the separator just before the quit/exit item. menu_filequititem the item which exits the application. menu_prefsseparator the separator just before the preferences/options item. menu_preferences the item which opens the application preferences. aboutseparator the separator just before the about item. aboutname the item which opens the about dialog for the applica...
PopupKeys - Archive of obsolete content
ou want to listen for keys pressed within a menu. note that the last argument here is true to listen for events during the capturing phase of event propagation: window.addeventlistener("keypress", someaction, true); however, the default listener provides all the suitable responses to keys, so there shouldn't be a need to handle keys yourself. while a menu is open, the focus remains where it was before the menu was open. for example, focusing a textbox and opening the textbox's context menu keeps the focus within the textbox. however, the capturing listener ensures that no key events reach the textbox while the menu is open. unlike with a menu, when a panel is opened, the focus is removed from any element that has it. this allows the focus to be shifted to elements within the panel. for more in...
Tooltips - Archive of obsolete content
hat when using a specialized tooltip element, any labels used inside it are not populated based on what the tooltip applies to, so you may need to set the content in a tooltip if you wish to use the same tooltip for several elements. this can be accomplished by using a popupshowing event listener and adjusting the tooltip as needed. the popupshowing event will be fired on the tooltip element just before the tooltip appears. for example: <tooltip id="iconic" onpopupshowing="this.lastchild.value = document.tooltipnode.label;"/> the document.tooltipnode property of the document holds the element that the mouse is hovering over. in this example, this property is examined to retrieve the label of the element that the mouse is over. this label is then set as the value of the last child of the toolt...
dateLeadingZero - Archive of obsolete content
...
hourLeadingZero - Archive of obsolete content
...
minuteLeadingZero - Archive of obsolete content
...
monthLeadingZero - Archive of obsolete content
...
secondLeadingZero - Archive of obsolete content
...
yearLeadingZero - Archive of obsolete content
...
statusbarpanel-iconic-text - Archive of obsolete content
...
Actions - Archive of obsolete content
not for every result. only the content at the element with the uri attribute and below is copied for each result. for example, if the example were modified to the following: <action> <toolbar> <button uri="?relateditem" label="?relateditem"/> </toolbar> </action> here, only the button would be repeated for each result; the toolbar will only be generated once. the toolbar is created just before the content for the first result is generated. the effect will be a toolbar with a set of three buttons inside it. of course, in this simple example you could really just make the toolbar the outer element with the datasources attribute rather than placing it inside the action. so far we have only been using the ?relateditem variable since that is really the only useful variable that is available...
Building Menus With Templates - Archive of obsolete content
ad been placed on the menuitem element. this causes the menupopup to only be created once. the menuitem elements however will be repeated for each result from the query. this makes sense, as we only want one menupopup to be created but multiple menuitem elements. the second button in the example displays an alert with the number of children the template-driven button has. if you press this button before opening the menu, there will be one child (the template itself). however, after the menu has been opened, there will be two children, one is the template and the other is the generated menupopup. note that the generated content does not get removed again when the menu is closed again; this extra feature of menus is only intended to be a performance enhancement to speed up the time it takes to dis...
Sorting Results - Archive of obsolete content
for each row. in almost all situations however, you would normally sort using the same variable used for the label value. however, one situation where this is not desirable is if the displayed values would not generate the correct order as there is a different representation that is more accurate. for example, the date 'may 15' would appear after 'august 24' when sorted purely alphabetically but before it when sorted chronologically. for rdf datasources, another way to sort by dates is to use the the parsetype="date" construct in the rdf datasource. this marks a literal as being a date value rather than a string. the builder will recognize this and sort chronologically instead. this also has the advantage that the dates will be displayed according to the user's current locale (meaning that the ...
Special Condition Tests - Archive of obsolete content
et to true, the rule will match as long as the member value or child of the starting node is an rdf container. we could also have left the rules in the original order and set the iscontainer on the first rule to false. the only thing we need to make sure is that the rules are in the proper order, so that the right data will be matched by the right rule. remember, the more specific rules should go before less specific rules. note that leaving out the iscontainer attribute is not the same as setting it to either true or false. if you don't use the iscontainer attribute, the rule will match regardless of whether the node is a container or not. the iscontainer attribute will also match containers appropriately if you have used the containment attribute in the template to change the predicates that i...
Template Builder Interface - Archive of obsolete content
<html:div id="photoslist" datasources="template-guide-photos5.rdf" ref="http://www.xulplanet.com/rdf/myphotos" xmlns:html="http://www.w3.org/1999/xhtml"> <html:h1>my photos</html:h1> <template> <html:p uri="rdf:*"><textnode value="rdf:http://purl.org/dc/elements/1.1/title"/></html:p> </template> </html:div> this example generates three paragraphs. some static content before the <template> element displays a <h1> header. since templates were designed for creating xul content, sometimes there can be unusual results when using html. sometimes this is due to 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 l...
Template Logging - Archive of obsolete content
nding> element is missing a predicate attribute the predicate attribute on a <binding> element has not been set. <binding> requires a variable for its object attribute the object attribute on a <binding> element has to be variable (a value beginning with a question mark). expected <content> to be first for an rdf template, when using the full query syntax, the <content> element must always appear before any other elements. in other words, this error occurs because either the <content> element was missing or was placed after a <member> or <triple> element. <member> requires a variable for its container attribute the container attribute on a <member> element has to be variable (a value beginning with a question mark). this error can also occur if the container attribute was not set. <member> requi...
Using Multiple Queries to Generate More Results - Archive of obsolete content
</rdf:seq> </r:people> </rdf:description> <rdf:description rdf:about="http://www.xulplanet.com/rdf/person/1" dc:title="nathan"/> <rdf:description rdf:about="http://www.xulplanet.com/rdf/person/2" dc:title="karen"/> we can then use two queries to generate results from different parts of the datasource. the first query will match the streets as before, but the second query will generate a result for each person. a header class is used to distinguish the content, although you could use exactly the same content if you wish. <template> <queryset> <query> <content uri="?start"/> <member container="?start" child="?item"/> </query> <rule> <binding subject="?item" predicate="http://purl.org/dc/elements/1.1/title" obje...
The Joy of XUL - Archive of obsolete content
the internet by clicking a link. conclusion mozilla, featuring xul, delivers a compelling technology for developing cross-platform applications with the same rich user interface and end user experience as native desktop applications. designers who are experienced in building web applications using w3c standard technologies can leverage this experience from the browser directly to the desktop. before the web became the standard for delivering applications to users across disparate desktops, this problem was solved with cross-platform client-server tools. but these offerings were invariably proprietary, cost a substantial amount of money per developer, and had runtime license fees that kept you humble and tightly tethered to the vendor. mozilla delivers much of the same value as these cross pl...
Complete - Archive of obsolete content
defaults/preferences directory containing a preferences file inside the jar there are three directories: content xul, javascript and other content that does not depend on the locale or theme locale files for each locale skin files for each theme version checks firefox etc. check extensions for compatibility before installing them. these version checks depend on the version numbers specified in the install.rdf file. there are two approaches: pessimistic and optimistic. the approach that is normally recommended is pessimistic. the extension is assumed to fail in any future version of the application. to adopt this approach, set the maxversion to the latest actual version where you have tested your extension.
SeaMonkey - making custom toolbar (SM ver. 1.x) - Archive of obsolete content
button in the toolbar. duplicate the last section. in the id and oncommand attributes, change 1 to 2. change the label, accesskey and tooltiptext attributes to whatever you want. do not change the class attribute. now edit button.css. duplicate the first two lines, changing the new lines to specify button-2. edit button.js and add javascript code for the new button. be sure to add the extra code before the curly brace on the last line of the file. for example, you could add this code for testing: 2: function () { alert("just testing again") }, create an image for the new button, naming the file button-2s.png. the images supplied here have a 256-colour palette and a transparent background. they are in png format. some other formats will also work. here are some more images that you can down...
Adding Event Handlers - Archive of obsolete content
s the xul window will load slightly faster. the src attribute is used to link in an external script file. our find files example let's add a script to the find file dialog. although it does not matter what the script file is called, usually it would be the same as the xul file with a .js extension. in this case, findfile.js will be used. add the line below just after the opening window tag and before any elements. <script src="findfile.js"/> we'll create the script file later when we know what we want to put in it. we'll define some functions in the file and we can call them in event handlers. you can include multiple scripts in a xul file by using multiple script tags, each pointing to a different script. you may use relative or absolute urls. for example, you may use urls of the follow...
Adding Methods to XBL-defined Elements - Archive of obsolete content
isible"); } else { document.getanonymousnodes(this)[0].setattribute("style","visibility: collapse"); } </body> </method> </implementation> </binding> the oncommand handlers here first get a reference to their parent bound element. (in this example, it is the box with the labeledbutton class). then, the 'showtitle' method is called, which functions as it did before. custom properties and methods are added only to the outer xul element the xbl is bound to. none of the elements declared inside the content tag have these properties or methods. this is why we have to get the parent first. the children of an element placed in the xul file can be retrieved in the normal way and don't move even if you use the children tag. for example: xul: <box id="outer" cla...
Additional Install Features - Archive of obsolete content
ate processing during the installation. for example, you may want to install a package only when certain conditions are met, such as having a particular library installed. in addition to the install object, a file object is also available during an installation script. it provides some functions which can be used to examine and modify files on disk. you can use these to move, copy or delete files before or after the files are installed. for example, you might want to make a backup of some files first. the following code will make a copy of the file "/bin/grep" and put it in the directory "/main". var binfolder = getfolder("file:///","bin"); var grep = getfolder(binfolder, "grep"); var mainfolder = getfolder("file:///", "main"); file.copy(grep, mainfolder); the first line will retrieve a r...
Advanced Rules - Archive of obsolete content
variable. let's say we wanted to add a weather prediction to the city datasource. the following conditions might be used: <conditions> <content uri="?list"/> <member container="?list" child="?city"/> <triple subject="?city" predicate="http://www.xulplanet.com/rdf/weather#prediction" object="?pred"/> </conditions> the template builder will iterate over each city as before. when it gets to the triple, it will look for an assertion in the rdf datasource for a city's weather prediction. the variable 'pred' will be assigned the prediction. the builder will repeat this for each of the four cities. a match occurs and the builder will generate content for each city that has a prediction. if the city has no prediction resource, the condition does not match and no content ...
Box Model Details - Archive of obsolete content
ally to fit their container, which in this case is the hbox. the align attribute controls this behavior on a horizontal box. you can also prevent this stretching by placing a maximum height on the elements or, better, on the box itself. if a box has a maximum height, the elements inside it are constrained by this. however, the problem with this is that you need to know how big the element will be beforehand. example 2 : source view <hbox flex="1" align="top"> <button label="left" style="min-width: 100px;" flex="1"/> <spacer flex="1"/> <button label="right" style="min-width: 100px;" flex="1"/> </hbox> summary of the box model to achieve complicated layouts, you will generally need to add nested boxes, specify minimum and maximum sizes on some elements, and make certain elements flexible. t...
Box Objects - Archive of obsolete content
here is also a corresponding css property -moz-box-orient which may be used instead, depending on the situation. this attribute was explained earlier in the section on boxes. ordinal attribute the ordinal attribute on an element may be used to specify the ordinal group of the element, or you can use the css property -moz-box-ordinal-group. elements with a lower ordinal value are placed in the box before elements with a higher ordinal value. for example, if one element has an ordinal of 2, it would be placed before an element with ordinal 3 or higher but after one with ordinal 1. the default value if the ordinal is not specified is 1. this means that if you want to change the displayed order of elements, you will often need to adjust the ordinals of several elements. adjusting the ordinal of an e...
Creating a Skin - Archive of obsolete content
ialog. 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 dialog before editing. you need to create a file 'findfile.css' in a custom skin. or, you can temporarily place it in the content directory and refer to it using a stylesheet directive. you can modify the existing findfile.css directly to see what it looks like, or you can create a custom skin and link to that. creating a custom skin package to create a skin, do the following: (if you are using firefox 1.
Creating a Wizard - Archive of obsolete content
sed respectively. these functions are called regardless of which page is currently displayed. to have different code called depending on which page you are on, use the onpagerewound or onpageadvanced attributes on a wizardpage element. they work in a similar way to the other functions except that you can use different code for each page. this allows you to validate the input entered on each page before the user continues. a third option is to use the onpagehide and onpageshow attributes on the wizardpage element. these methods will be called when the page is hidden or shown, regardless of which button was pressed (except when cancel is pressed -- you need to use onwizardcancel to check for this.) these three methods should provide enough flexibility to handle navigation as you need to. the fo...
Cross Package Overlays - Archive of obsolete content
rowser-toolbox</code>" in firefox 3 beta 3. you can support both firefox 2 and earlier and firefox 3 by duplicating the <code><span class="plain">' .. <toolbox> .. '</span></code> section with that id. to add this overlay to the manifest file, we need to add two resources. first, we add one for each window that we are applying an overlay to. the code below should be added into contents.rdf just before the closing rdf tag. <rdf:seq about="urn:mozilla:overlays"> <rdf:li resource="chrome://navigator/content/navigator.xul"/> </rdf:seq> this declares that we are adding a overlay window, a child of the root overlay node (urn:mozilla:overlays). you can add additional nodes for any other windows that you want to apply overlays to by adding additional li nodes. next, we add a node for each ove...
Custom Tree Views - Archive of obsolete content
uld implement are listed below. rowcount this property should be set to the total number of rows in the tree. getcelltext( row , column ) this method should return the text contents at the specified row and column. this will be called to display data for each cell. the rows are supplied as numeric values starting at 0. the columns are treecolumn objects. in the older versions of mozilla (before firefox 1.5 or mozilla 1.8), the columns are supplied as the values of the id attribute on the columns. if you need a id attribute like older versions, the id property of treecolumn can be used. settree( tree ) this method is called once to set the tree element on the view. here is an example of defining such as object, which can be called whatever you want: //moz 1.8 var treeview = { ro...
Document Object Model - Archive of obsolete content
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 you can call functions of the new window from the opener. it is important to note, however, that the open() method returns before the window has fully loaded, so functions will not typically be available yet. the window object isn't defined by any dom specification, but in mozilla is sometimes considered part of dom level 0, a name used by some developers to refer to the dom-like functions before they were added to specifications. the actual document displayed in a window can be retrieved using the window's document proper...
Input Controls - Archive of obsolete content
ml textarea, you can use the rows and cols attributes to set the size. this should be set to the number of rows and columns of characters to display. our find files example let's add a search entry field to the find file dialog. we'll use the textbox element. <label value="search for:" control="find-text"/> <textbox id="find-text"/> <button id="find-button" label="find"/> add these lines before the buttons we created in the last section. if you open this window, you will see something much like that shown in the image. notice that the label and the text input field have now appeared in the window. the textbox is fully functional and you can type into it and select text. note that the control attribute has been used so that the textbox is selected when the label is clicked. checkboxes...
Install Scripts - Archive of obsolete content
cript 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 means that you can call the methods of the window object with the qualifier before it, which means that window.open() can simply be written open(). in an install script, there is no associated window, however the global object will be an install object which contains a number of functions to customize the install process. some of the install object's functions will be described below. the install script should take the following steps: initialize the installation by specifyi...
Manipulating Lists - Archive of obsolete content
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 fired we can assume that an item is selected. in other cases, you may wish to check to ensure that selecteditem is not null before continuing. the select event is also fired when a radio button in a radiogroup is selected and when a tab is selected in a tabs element. however, menulists do not fire the select event; instead you can listen to the command event to handle when an item is selected. for the tabs element, it is often more convenient to use functions of the tabbox element instead. it also has a selectedindex funct...
More Tree Features - Archive of obsolete content
ayed 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 will set the open attribute to reflect the 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. example hierarchical tree the following is a simple example: example 1 : source view <tree rows="6"> <treecols> <treecol id="firstname" label="first name" primary="true" flex="...
Open and Save Dialogs - Archive of obsolete content
the file picker. this function takes three arguments, the window that is opening the dialog, the title of the dialog and the mode. the mode here is modeopen which is used for an open dialog. you can also use modegetfolder and modesave for the other two modes. these modes are constants of the nsifilepicker interface. default directory and filters there are two features you can set of the dialog before it is displayed. the first is the default directory that is displayed when the dialog is opened. the second is a filter that indicates the list of file types that are displayed in the dialog. this would be used, for example, to hide all but .html files. you can set the default directory by setting the displaydirectory property of the file picker object to a directory. the directory should b...
RDF Datasources - Archive of obsolete content
ystem (usually the list of drives) a file url by using a file url for the ref attribute, you can select a specific directory to be returned. for example, you might use file:///windows or files:///usr/local. the files datasource is an example of a datasource that determines its resources only when necessary. we don't want every file in the filesystem to be determined before the data is displayed. instead, only the files and directories that the tree element (or other elements) will need to display at a given time will be determined. composite datasources you can specify multiple datasources in the datasources attribute by separating them with whitespace as in the example below. this has the effect of reading the data from all the datasources mentioned. <tree datasou...
Skinning XUL Files by Hand - Archive of obsolete content
u want to use the classes already defined in mozilla's global skin to style your elements, you may do so. but you may also want to define new classes of buttons particular to your xul file, in which case the style information will be wholly defined within your custom css file. reading the global skin it's very important to familiarize yourself with the basic style definitions in the global skin before you set out creating your own stylesheet. css can quickly become complicated. the ability to apply styles to elements of a type, to specifically identified elements, and to classes of elements creates the potential for redundancies or conflicts in the style information. to avoid this, the makers of the css specification have created some rules of precedence that look at how many different rules h...
Tabboxes - Archive of obsolete content
h"/> <checkbox id="wordscheck" label="match entire filename"/> </tabpanel> </tabpanels> </tabbox> the tab elements have been placed around the main content of the window. you can see the two tabs, search and options. clicking on each one will bring up the respective tab pages. as shown by the image, the two options appear on the second tab. the first tab looks pretty much like it did before, apart from the tabs along the top. find files example so far : source view next, we'll look at how to create grids of content. « previousnext » ...
Trees - Archive of obsolete content
Archive › Mozilla › XUL › Tutorial › Trees
the second column will appear twice as wide due to the larger flexibility. a single row has been added to demonstrate what the table would look like with a row. in a real implementation, the rows would be added by a script as the search was performed, or a custom view would be created t...
XBL Example - Archive of obsolete content
ument.getanonymousnodes(this)[0].childnodes[0]; get the first element of the anonymous content array, which will be the vertical box, then get its first child, which will be the deck element. var totalpages=this.childnodes.length; get the number of children that the bound box has. this will give the total number of pages that there are. if (newidx<0) return 0; if the new index is before the first page, don't change the page and return 0. the page should not change to a value earlier than the first page. if (newidx>=totalpages) return totalpages; if the new index is after the last page, don't change the page and return the last page's index. the page should not change to one after the last page. thedeck.setattribute("selectedindex",newidx); change the selectedindex ...
XPCOM Examples - Archive of obsolete content
which returns an object which implements nsisimpleenumerator. this can be used to iterate over all of the cookies. an enumerator has a hasmoreelements() method which will return true until we get to the last cookie. the getnext() method gets a cookie and moves the enumerator index to the next cookie. since an enumerator just returns a generic object, we need to queryinterface() it to an nsicookie before we can use it. in this case, we just use the instanceof operator to accomplish this. finally, an item is added to the menu for the cookie. the host, name and value properties of the cookie are used for this. menus have an appenditem() function which can be used to add an item to the menu, given a label and a value. see also more examples are available below. code snippets http://kb.mozillazi...
Using Remote XUL - Archive of obsolete content
/global/skin/, is a reference to the default application stylesheet (a.k.a. skin). if we were to switch the browser to a different skin, the style of our menus would also change. if we want our site to have the same look no matter what skin the user is using, we would need to write our own stylesheet to style the elements. in case you're wondering, the reason the buttons and menu items had style before we added the stylesheet reference is that some xul elements are defined in mozilla using another xml-based language called xbl which provides building blocks for creating ui widgets. xbl files sometimes contain references to the default application stylesheet, and when they do their widgets inherit that style even if we don't specify a stylesheet. you can't count on this behavior, however, so you...
Using Visual Studio as your XUL IDE - Archive of obsolete content
1. setting the correct editor as xul files are nothing but xml, you can use the normal xml-editor for writing xul. go to tools > options... ...
Writing Skinnable XUL and CSS - Archive of obsolete content
in the xul file. it should instead take place through the chrome registry. examples of overlays that should take place using the chrome registry include the security padlock icon and any messenger ui in the navigator window. style="..." is prohibited in xul files without approval any usages of inline style are extremely dangerous, since they are overriding the included skin, and must be approved before their usage will be allowed. image chrome urls should never occur in xul. any chrome url that references an image in the skin is strictly forbidden in the xul. if you find yourself needing to display an image from the skin, then use <titledbutton> and style it rather than using <html:img>. the problem here is that you'll end up placing a restriction on the skin, which will force the skin designe...
XUL Accesskey FAQ and Policies - Archive of obsolete content
el="apply instantly" accesskey="a" /> apply instantly in mozilla, we use dtd's for one more layer of abstraction, for purposes of internationalization. the above example should say: <button label="apply instantly" accesskey="&applyinstantly.accesskey" /> (always use accesskey instead of akey). if methods like confirm(), confirmex() or prompt() are being used to create a dialog, use an & before the button or checkbox text to make the next character an accesskey. for example, "do it &now" makes "n" the underlined accesskey. to insert a real ampersand, use &&. how do i pick an accesskey letter? accesskey attribute is case sensitive! notice that the difference between the button examples above is the case of the accesskey specified. mozilla's accesskey implementation will first try...
XUL FAQ - Archive of obsolete content
st of projects (dead and active) aiming to create a xul ide/editor is at wikimo:xul:ide. troubleshooting prefwindow-based options windows this ought to be on a separate page, preferences system troubleshooting. it is a faq. ...
The Implementation of the Application Object Model - Archive of obsolete content
a red x in the tree view.) some change has been made in the composite data source that is the equivalent of a local annotation to the xul file. in this case, rdf will do one of two things. if the xul stream came from a remote site, then rdf has no choice but to make a local annotation on the graph. if the xul stream came from a local file, then rdf can either locally annotate the graph (just as before), or it can serialize the xul and write over the original file (thus allowing local changes to a local file to be reflected right in the xul). referencing local data: the localdata attribute a tag that references local rdf data does so by using the localdata attribute, which gives the uri of the local data that should be merged in with the xul content tree. examples of tags that can reference ...
XUL controls - Archive of obsolete content
richlistbox reference related elements: richlistitem <scale> a scale displays a bar with a thumb that may be slid across the bar to select between a range of values. <scale min="1" max="10"/> scale reference <splitter> allows the user to adjust the division of space between elements. <splitter collapse="before"> <grippy/> </splitter> splitter reference related elements: grippy <tab> description goes here. <tab label="firefox"/> tab reference related elements: tabs tabbox tabpanels <textbox> a textbox which allows a single line of text to be entered. <textbox value="firefox"/> more informati...
button - Archive of obsolete content
aredocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), removeattributenode(), removeattributens(), removechild(), removeeventlistener(), replacechild(), setattribute(), setattributenode(), setattributenodens(), setattributens(), setuserdata related interfaces nsiaccessibleprov...
caption - Archive of obsolete content
aredocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), removeattributenode(), removeattributens(), removechild(), removeeventlistener(), replacechild(), setattribute(), setattributenode(), setattributenodens(), setattributens(), setuserdata related elements groupbox,...
checkbox - Archive of obsolete content
aredocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), removeattributenode(), removeattributens(), removechild(), removeeventlistener(), replacechild(), setattribute(), setattributenode(), setattributenodens(), setattributens(), setuserdata related interfaces nsiaccessibleprov...
colorpicker - Archive of obsolete content
aredocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), removeattributenode(), removeattributens(), removechild(), removeeventlistener(), replacechild(), setattribute(), setattributenode(), setattributenodens(), setattributens(), setuserdata related interfaces nsidomxulcontrole...
command - Archive of obsolete content
aredocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), removeattributenode(), removeattributens(), removechild(), removeeventlistener(), replacechild(), setattribute(), setattributenode(), setattributenodens(), setattributens(), setuserdata related xul:list of commands ...
commandset - Archive of obsolete content
aredocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), removeattributenode(), removeattributens(), removechild(), removeeventlistener(), replacechild(), setattribute(), setattributenode(), setattributenodens(), setattributens(), setuserdata ...
description - Archive of obsolete content
aredocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), removeattributenode(), removeattributens(), removechild(), removeeventlistener(), replacechild(), setattribute(), setattributenode(), setattributenodens(), setattributens(), setuserdata style classes header a class used fo...
dialog - Archive of obsolete content
node(), comparedocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), removeattributenode(), removeattributens(), removechild(), removeeventlistener(), replacechild(), setattribute(), setattributenode(), setattributenodens(), setattributens(), setuserdata acceptdialog() return type: no ...
dialogheader - Archive of obsolete content
aredocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), removeattributenode(), removeattributens(), removechild(), removeeventlistener(), replacechild(), setattribute(), setattributenode(), setattributenodens(), setattributens(), setuserdata related elements dialog, window ...
editor - Archive of obsolete content
aredocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), removeattributenode(), removeattributens(), removechild(), removeeventlistener(), replacechild(), setattribute(), setattributenode(), setattributenodens(), setattributens(), setuserdata related interfaces nsiaccessibleprov...
image - Archive of obsolete content
Archive › Mozilla › XUL › image
aredocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), removeattributenode(), removeattributens(), removechild(), removeeventlistener(), replacechild(), setattribute(), setattributenode(), setattributenodens(), setattributens(), setuserdata style classes alert-icon ...
key - Archive of obsolete content
Archive › Mozilla › XUL › key
aredocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), removeattributenode(), removeattributens(), removechild(), removeeventlistener(), replacechild(), setattribute(), setattributenode(), setattributenodens(), setattributens(), setuserdata details on key, keycode, and modifiers a...
label - Archive of obsolete content
Archive › Mozilla › XUL › label
aredocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), removeattributenode(), removeattributens(), removechild(), removeeventlistener(), replacechild(), setattribute(), setattributenode(), setattributenodens(), setattributens(), setuserdata style classes the following classes may b...
listcell - Archive of obsolete content
aredocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), removeattributenode(), removeattributens(), removechild(), removeeventlistener(), replacechild(), setattribute(), setattributenode(), setattributenodens(), setattributens(), setuserdata style classes listcell-iconic use th...
listitem - Archive of obsolete content
aredocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), removeattributenode(), removeattributens(), removechild(), removeeventlistener(), replacechild(), setattribute(), setattributenode(), setattributenodens(), setattributens(), setuserdata style classes the following classes may...
menu - Archive of obsolete content
Archive › Mozilla › XUL › menu
node(), comparedocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), removeattributenode(), removeattributens(), removechild(), removeeventlistener(), replacechild(), setattribute(), setattributenode(), setattributenodens(), setattributens(), setuserdata appenditem( label, value ) ...
menubar - Archive of obsolete content
aredocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), removeattributenode(), removeattributens(), removechild(), removeeventlistener(), replacechild(), setattribute(), setattributenode(), setattributenodens(), setattributens(), setuserdata related elements menu, menuitem, men...
menuitem - Archive of obsolete content
aredocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), removeattributenode(), removeattributens(), removechild(), removeeventlistener(), replacechild(), setattribute(), setattributenode(), setattributenodens(), setattributens(), setuserdata style classes menuitem-iconic use th...
menulist - Archive of obsolete content
node(), comparedocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), removeattributenode(), removeattributens(), removechild(), removeeventlistener(), replacechild(), setattribute(), setattributenode(), setattributenodens(), setattributens(), setuserdata appenditem( label, value, description )...
menuseparator - Archive of obsolete content
aredocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), removeattributenode(), removeattributens(), removechild(), removeeventlistener(), replacechild(), setattribute(), setattributenode(), setattributenodens(), setattributens(), setuserdata related elements menu, menubar, menu...
notification - Archive of obsolete content
node(), comparedocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), removeattributenode(), removeattributens(), removechild(), removeeventlistener(), replacechild(), setattribute(), setattributenode(), setattributenodens(), setattributens(), setuserdata close() return type: no return value ...
param - Archive of obsolete content
Archive › Mozilla › XUL › param
aredocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), removeattributenode(), removeattributens(), removechild(), removeeventlistener(), replacechild(), setattribute(), setattributenode(), setattributenodens(), setattributens(), setuserdata ...
preference - Archive of obsolete content
aredocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), removeattributenode(), removeattributens(), removechild(), removeeventlistener(), replacechild(), setattribute(), setattributenode(), setattributenodens(), setattributens(), setuserdata events change when a preference valu...
prefpane - Archive of obsolete content
aredocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), removeattributenode(), removeattributens(), removechild(), removeeventlistener(), replacechild(), setattribute(), setattributenode(), setattributenodens(), setattributens(), setuserdata events paneload this event...
radio - Archive of obsolete content
Archive › Mozilla › XUL › radio
aredocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), removeattributenode(), removeattributens(), removechild(), removeeventlistener(), replacechild(), setattribute(), setattributenode(), setattributenodens(), setattributens(), setuserdata related elements radiogroup, checkbo...
radiogroup - Archive of obsolete content
node(), comparedocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), removeattributenode(), removeattributens(), removechild(), removeeventlistener(), replacechild(), setattribute(), setattributenode(), setattributenodens(), setattributens(), setuserdata appenditem( label, value ) ...
richlistitem - Archive of obsolete content
aredocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), removeattributenode(), removeattributens(), removechild(), removeeventlistener(), replacechild(), setattribute(), setattributenode(), setattributenodens(), setattributens(), setuserdata related interfaces nsiaccessibleprov...
rule - Archive of obsolete content
Archive › Mozilla › XUL › rule
aredocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), removeattributenode(), removeattributens(), removechild(), removeeventlistener(), replacechild(), setattribute(), setattributenode(), setattributenodens(), setattributens(), setuserdata ...
scale - Archive of obsolete content
Archive › Mozilla › XUL › scale
aredocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), removeattributenode(), removeattributens(), removechild(), removeeventlistener(), replacechild(), setattribute(), setattributenode(), setattributenodens(), setattributens(), setuserdata decrease() return type: no...
scrollbar - Archive of obsolete content
aredocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), removeattributenode(), removeattributens(), removechild(), removeeventlistener(), replacechild(), setattribute(), setattributenode(), setattributenodens(), setattributens(), setuserdata ...
tabbox - Archive of obsolete content
aredocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), removeattributenode(), removeattributens(), removechild(), removeeventlistener(), replacechild(), setattribute(), setattributenode(), setattributenodens(), setattributens(), setuserdata related elements tabs, tab, tabpanel...
tabs - Archive of obsolete content
Archive › Mozilla › XUL › tabs
node(), comparedocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), removeattributenode(), removeattributens(), removechild(), removeeventlistener(), replacechild(), setattribute(), setattributenode(), setattributenodens(), setattributens(), setuserdata advanceselectedtab( dir, wrap ) retur...
toolbarbutton - Archive of obsolete content
aredocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), removeattributenode(), removeattributens(), removechild(), removeeventlistener(), replacechild(), setattribute(), setattributenode(), setattributenodens(), setattributens(), setuserdata related elements toolbar, toolba...
treecell - Archive of obsolete content
aredocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), removeattributenode(), removeattributens(), removechild(), removeeventlistener(), replacechild(), setattribute(), setattributenode(), setattributenodens(), setattributens(), setuserdata related elements tree, treecols, tre...
treeitem - Archive of obsolete content
aredocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), removeattributenode(), removeattributens(), removechild(), removeeventlistener(), replacechild(), setattribute(), setattributenode(), setattributenodens(), setattributens(), setuserdata related elements tree, treecols, tre...
window - Archive of obsolete content
aredocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), removeattributenode(), removeattributens(), removechild(), removeeventlistener(), replacechild(), setattribute(), setattributenode(), setattributenodens(), setattributens(), setuserdata see also: dom window object methods no...
wizard - Archive of obsolete content
node(), comparedocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), removeattributenode(), removeattributens(), removechild(), removeeventlistener(), replacechild(), setattribute(), setattributenode(), setattributenodens(), setattributens(), setuserdata « xul reference home advance( ...
wizardpage - Archive of obsolete content
aredocumentposition, dispatchevent(), docommand, focus, getattribute(), getattributenode(), getattributenodens(), getattributens(), getboundingclientrect(), getclientrects(), getelementsbyattribute, getelementsbyattributens, getelementsbyclassname(), getelementsbytagname(), getelementsbytagnamens(), getfeature, getuserdata, hasattribute(), hasattributens(), hasattributes(), haschildnodes(), insertbefore(), isdefaultnamespace(), isequalnode, issamenode, issupported(), lookupnamespaceuri, lookupprefix, normalize(), queryselector(), queryselectorall(), removeattribute(), removeattributenode(), removeattributens(), removechild(), removeeventlistener(), replacechild(), setattribute(), setattributenode(), setattributenodens(), setattributens(), setuserdata related wizard ...
XULRunner 1.8.0.1 Release Notes - Archive of obsolete content
xulrunner 1.8.0.1 is the first stable developer preview release of xulrunner. it provides facilities for launching standalone xul applications and embedding apis which can be used to render web pages within native and java applications. xulrunner 1.8.0.4 is now available as a security/stability update; all users should install this new version. system requirements before installing, make sure your computer meets the 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 a archive too...
XULRunner 1.8.0.4 Release Notes - Archive of obsolete content
view of the mozilla xulrunner application framework. it replaces version 1.8.0.1; all users should upgrade. it provides facilities for launching standalone xul applications and embedding apis which can be used to render web pages within native and java applications. as of december 2008,xulrunner 1.9.0.4 is available in the "gecko 1.9.0" branch upon which firefox 3 is based. system requirements before installing, make sure your computer meets the 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 direct...
XULRunner 1.9.1 Release Notes - Archive of obsolete content
n framework. it provides facilities for launching standalone xul applications and embedding apis which can be used to render web pages within native and java applications. xulrunner 1.9.1.x is built from the same source code snapshot as firefox 3.5.x. current version the current version of xulrunner is 1.9.1.19, matching firefox 3.5.19 detailed release notes can be found here. system requirements before installing, make sure your computer meets the 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 directo...
XULRunner 1.9.2 Release Notes - Archive of obsolete content
amework. it provides facilities for launching standalone xul applications and embedding apis which can be used to render web pages within native and java applications. xulrunner 1.9.2.x is built from the same source code snapshot as firefox 3.6.x. current version the current version of xulrunner 1.9.2 is 3.6.26, matching firefox 3.6.26 detailed release notes can be found here. system requirements before installing, make sure your computer meets the 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...
XULRunner 1.9 Release Notes - Archive of obsolete content
should upgrade. it provides facilities for launching standalone xul applications and embedding apis which can be used to render web pages within native and java applications. xulrunner 1.9 is built from the same source code snapshot as firefox 3. current version the current version of xulrunner is 1.9.0.17, matching firefox 3.0.17 detailed release notes can be found here. system requirements before installing, make sure your computer meets the 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 direct...
XULRunner 2.0 Release Notes - Archive of obsolete content
ication framework. it provides facilities for launching standalone xul applications and embedding apis which can be used to render web pages within native and java applications. xulrunner 2.0.x is built from the same source code snapshot as firefox 4.0.x. current version the current version of xulrunner 2.0 is 2.0, matching firefox 4.0 detailed release notes can be found here. system requirements before installing, make sure your computer meets the system requirements (nb: that page will change for firefox 4 shipping). 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. the releases directory can be found here. specific runtimes can be found at: download xulrunn...
Creating XULRunner Apps with the Mozilla Build System - Archive of obsolete content
itution in the manifest for the variable to be expanded). you will also need to include a branding/ subdirectory. follow the example in mccoy carefully since xulrunner is sensitive about having exactly the right files in exactly the right packages. the components/ subdirectory if you are reading this guide, you probably need to include c++ components in your application. if you've never done this before, you should consult creating xpcom components or another xpcom reference. the public/ and src/ directories that you put in the components/ directory will look the same as for an extension that includes c++ components, so you can use the relevant sections of creating custom firefox extensions with the mozilla build system as a reference. the makefiles, however, will be difference since you won't b...
Creating a Windows Inno Setup installer for XULRunner applications - Archive of obsolete content
start pack, you can later get istool from inno setup third-party files. step 2: creating the application to make your application standalone, deploy your application according to the deploying xulrunner 1.8 article. my app's example follows. myapp/ application.ini chrome/ default/ myapp.exe (copy xulrunner-stub.exe and rename) xulrunner/ please test your application before deploying it. if your application does not run, neither will the installed version. step 3: creating the inno setup script create an inno setup script (.iss file). the inno setup script wizard can't set chrome directory's deployment 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 app...
Dialogs in XULRunner - Archive of obsolete content
eating an application easier for developers; in addition, the consistent user experience also makes applications easier to use. xul supports native implementations of filepickers (mozilla terminology for file open and save dialogs). newer releases will allow using preferences to switch to a xul emulation filepicker, if you want to. ...
Make your xulrunner app match the system locale - Archive of obsolete content
this article is going to assume a lot of knowledge of xpcom and will be written for someone using python, but the ideas should be adaptable. also, this may not be the proper way to do this and it may not work for you in all cases. please update if there are more correct ways to do this. the first step is to get the code we're about to write to run before any of the locale specific resources are loaded. democracy does this by creating a command line handler called democracyclh, and then creating a new object of our pybridge component. the code described lives in the pybridge component's onstartup method which gets called automatically. the second step is to figure out the system locale. to be finished later. then set the locale preference. the following is python code to set this preferen...
Using SOAP in XULRunner 1.9 - Archive of obsolete content
2c42 < var jsout = $.xmltojson(xdata.responsexml); --- > var jsout = xmlobjectifier.xmltojson(xdata.responsexml); 46,60c46,62 < $.ajax({ < type: "post", < url: soapclient.proxy, < datatype: "xml", < processdata: false, < data: content, < complete: getresponse, < contenttype: soapclient.contenttype + "; charset=\"" + soapclient.charset + "\"", < beforesend: function(req) { < req.setrequestheader("method", "post"); < req.setrequestheader("content-length", soapclient.contentlength); < req.setrequestheader("soapserver", soapclient.soapserver); < req.setrequestheader("soapaction", soapreq.action); < } < }); --- > var xhr = new xmlhttprequest(); > xhr.mozbackgroundrequest = true; > xhr.open('post', soapclie...
application/http-index-format specification - Archive of obsolete content
ists of one or more white space separated tokens that represent data described by a previous 200 line. tokens may be quoted or unquoted. unquoted tokens may not contain white space. quoted tokens are terminated by the next quote but may not contain carrage returns or new lines. any illegal characters must be escaped via the url escaping syntax defined by rfc 1738. note that a 201 line encountered before a 200 line should be ignored. 300 a url pointing to the directory represented by the index if there is one. a valid path token must be url escaped. valid 200 tokens note that all tokens are case insensitive. filename the name of file that can be used to retrieve the file when combined with the full path provided by the 300 line. white space and 8 bit characters must be url encoded. con...
calICalendarView - Archive of obsolete content
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 been assigned to the view, before calling any of the methods it implements.note that in most cases, this attribute will be set by the consumers of calicalendarview very early in an application/extension's loading process. startdate returns a calidatetime corresponding to the first date shown by the view enddate returns a calidatetime corresponding to the last date shown by the view. note that this date is typically not imme...
2006-10-13 - Archive of obsolete content
dering problem with firefox print on the firefox context menu user would like discussion about why the bug https://bugzilla.mozilla.org/show_bug.cgi?id=204519 is a wontfix. (user feels print belongs on the context menu along with back, reload, etc.) questions about programming for firefox a student questions how to create an extension that changes fonts, and how to capture website content before it is displayed. firefox add-on wanted user is inquiring if there is such an application to automatically save pieces of a webpage everytime is it updated. firefox 2.0 should re-implement modal window.open to support web 2.0 user would like the option to show pop-up windows, using window.open(), from inside untrusted script, to be re-implemented. this function was disabled, see bug: https...
2006-11-10 - Archive of obsolete content
ovember 4, 2006 - november 10, 2006 announcements none this week. discussions site-specific search using our search box a discussion surrounding implementing a way to search a current page with the page's embedded search component and how to make this efficient and usable. event in firefox similar to ondownloadcomplete event in ie an inquiry about how to change the font of a web page before it is displayed using an extenstion. favicon as microsummary/feed/other stuff indicator suggestion about making the favicon create a bookmark for the page with a microsummary. firefox 2.0 - net accessed when bookmark properties viewed question about whether firefox 2.0 downlads the web page again when the properties of the bookmark are viewed. followed by a discussion whether this is an i...
2006-10-13 - Archive of obsolete content
gcc-and-visibility-one-step-forward-hit-a-brick-wall announcements please help us test the new tinderbox and bonsai server installations paul reed announced that they are setting up a new installation of the tinderbox and bonsai servers onto new, supported hardware. some testing and validation has been done, but they would like other people to look at the installations and complete the setup before they switch over. new tinderbox installation new bonsai installation if any inconsistencies are found please use bugzilla to let them know discussions there were no discussions this week. meetings there were no meetings this week. ...
Extentsions FAQ - Archive of obsolete content
gest the best way to do source level debugging in a firefox extension? in the debug menu, uncheck exclude browser files. use the debugger by typing in a command like this: /break chrome://myextension/content/myfile.js 123 then i suggest using flat chrome. if you turn off the xul cache you don't even need to restart to see changes, simply open a new window. how can i backup some of the files before upgrade an extension and put them back afterward? do i need to write an installation script to achieve this? you shouldn't store data there, so there's nothing to backup. do not store files within the extension directory. the profile directory is ment to do so. storing files within the extension directory is a no-no because it might break the multi-user support of those mozilla products, as ...
2006-10-20 - Archive of obsolete content
announced by tim on friday october 13, 2006. help required designing new home for quality.mozilla.org - talented web designers and/or artists interested in helping the design for quality.mozilla.org please read this posting. ...
2006-12-01 - Archive of obsolete content
s with rhino/js. it is basically a java classloader that creates classes from javascript files. server side spidermonkey juicescript is an open source version of a server side javascript. it supports a apache2 module and stand alone version. http://www.juicescript.org/ discussions deleting objects in spidermonkey a user asks if there's a method of manually deleting an object in spidermonkey before garbage collector deletes it. peter wilson's reply was to add a method that does the deleting with a native implementation that releases the resources held by the object as seen in this database interface: var mydbase = new pgsqlconnection; mydbase.connect("database"); mydbase.exec("select * from mytable where ..."); // use the result data - (native implementation function) mydbase.close() sp...
2006-12-24 - Archive of obsolete content
2006 announcements none this week. discussions [reset issue for overflow='hidden' in ie and opera there is a very modest horizontal shift of the document due to reflow associated with the removal of the vertical scroll bar (because the document content is using a horizontal centering style). but in firefox the document is reset (shifted both horizontally and vertically) to its 0,0 position before being centered horizontally. ...
2006-12- 02 - Archive of obsolete content
2006 announcements none this week. discussions [reset issue for overflow='hidden' in ie and opera there is a very modest horizontal shift of the document due to reflow associated with the removal of the vertical scroll bar (because the document content is using a horizontal centering style). but in firefox the document is reset (shifted both horizontally and vertically) to its 0,0 position before being centered horizontally. ...
2006-12-01 - Archive of obsolete content
summary: mozilla.dev.tech.xpcom - nov 25- dec 01, 2006 announcements none during this week. discussions nsicontentpolicy and user interaction the proper way to get user confirmation before trying to load certain file types. debugging firefox extesnion? a tip on how to debug firefox extensions using a debugger. segmentation fault while running the browser browser crashes after installation of subjects extension. meetings none during this week. ...
Monitoring plugins - Archive of obsolete content
runtime is a measure of cpu use, however, it is a good representation of overall resources being consumed 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. below are a number of javascript snippets that would be useful to developers trying to use this feature: registration to register for runtime notifications with the observer service you must create a class with an observe method which receives 3 parameters (subject, topic and data) as well as a register ...
NPFullPrint - Archive of obsolete content
inter to an npprint object (previously allocated by the browser). the npfullprint structure is used when the mode field of npprint is set to np_full. the pluginprinted field of this structure determines whether the plug-in prints in full-page mode or not. if you want the plug-in to take complete control of the printing process, it should print the full page and set the field pluginprinted to true before returning. if you want an embedded plug-in to simply render its area of the page, set pluginprinted to false and return immediately; the browser calls npp_print again with the npembedprint substructure of npprint. see also npp_print, npprint, npembedprint ...
NPN_CreateObject - Archive of obsolete content
rns the newly-allocated npobject. description if the given npclass provides an allocate function it is used to allocate the storage for the object and the npp argument passed to npn_createobject() is passed along to that function. if no allocate function is provided, malloc() is called to allocate enough memory to hold an npobject. the newly created npobject's reference count is initialized to 1 before it is returned. ...
NPN_InvalidateRect - Archive of obsolete content
ts its contents. syntax #include <npapi.h> void npn_invalidaterect(npp instance, nprect *invalidrect); parameters the function has the following parameters: instance pointer to the plug-in instance to invalidate a portion of. invalidrect the area to invalidate, specified in a coordinate system that originates at the top left of the plug-in's content area. description before a windowless plug-in can repaint or refresh part of its drawing area, the plug-in must first invalidate the area with either npn_invalidaterect() or npn_invalidateregion(). npn_invalidaterect() causes the npp_handleevent() method to pass an update event or a paint message to the plug-in. after calling this method, the plug-in receives a paint message asynchronously. the browser redraws invalid ar...
NPN_InvalidateRegion - Archive of obsolete content
nting or refreshing a windowless plug-in. syntax #include <npapi.h> void npn_invalidateregion(npp instance, npregion invalidregion); parameters the function has the following parameters: instance pointer to the current plug-in instance. invalidregion the area to invalidate, specified in a coordinate system that originates at the top left of the plug-in. description before a windowless plug-in can repaint or refresh part of its drawing area, the plug-in must first invalidate the area with either npn_invalidaterect() or npn_invalidateregion(). npn_invalidateregion() causes the npp_handleevent() method to pass an update event or a paint message to the plug-in. if a plug-in calls this method, it receives a paint message later. the browser redraws invalid areas of the ...
NPN_MemFlush - Archive of obsolete content
ed memory, in bytes. if no memory can be freed, the browser returns 0. description the plug-in calls npn_memflush() when it is not possible to call npn_memalloc(), for example, when calling system apis that indirectly allocate memory. to request that the browser free as much memory as possible, call npn_memflush() repeatedly until it returns 0. on the mac, you can use this method to free memory before calling memory-intensive system calls. in general, plug-ins should use npn_memalloc() to allocate memory in the browser's memory space, since this function automatically frees cached data if necessary to fulfill the request. see also npn_memfree() ...
NPN_Status - Archive of obsolete content
the browser does. if your plug-in has a button or other object that acts as a link when clicked, you can call npn_status() to display a description or url when the user moves the cursor over it. the browser always displays the last status line message it receives, regardless of the message source. your message is always displayed, but you have no control over how long it stays in the status line before another message replaces it. see also npn_useragent() npp ...
NPP_SetWindow - Archive of obsolete content
us platform-specific data. this window is valid for the life of the instance, or until npp_setwindow is called again with a different value. for windowed plug-ins on windows and unix, the window parameter contains a handle to a subwindow of the browser window hierarchy. on mac os, this field points to an np_port structure. for windowless plug-ins, it is a platform-specific handle to a drawable. before setting the window parameter to point to a new window, it is a good idea to compare the information about the new window to the previous window (if one existed) to account for any changes. for windowless plugins, npp_setwindow is called with a cliprect of 0,0,0,0 to signal that the plugin is not visible. note: npp_setwindow is useful only for embedded (np_embed) or full-screen (np_full) plug-i...
NPP_WriteReady - Archive of obsolete content
the plug-in can consume. syntax #include <npapi.h> int32 npp_writeready(npp instance, npstream* stream); parameters the function has the following parameters: instance pointer to the current plug-in instance. stream pointer to the current stream. returns returns the maximum number of bytes that an instance is prepared to accept from the stream. description the browser calls npp_writeready before each call to npp_write to determine whether a plug-in can receive data and how many bytes it can receive. this function allows the browser to send only as much data to the instance as it can handle at one time, making resource use more efficient for both the browser and plug-in. the npp_write function may pass a larger buffer, but the plug-in is required to consume only the amount of data returne...
NPStream - Archive of obsolete content
, notifydata is set to the value of the notifydata parameter to npn_geturlnotify or npn_posturlnotify. for other streams, notifydata is null. headers the response headers from the host. this field is only available if the np version is greater than or equal to npvers_has_response_headers. this field is used only for http and is null for other types of streams. the plug-in should copy this data before making use of it. the headers include the http status line and all headers, verbatim as received from the server. lines are terminated by newline characters ("\n"), and the headers are terminated by a newline followed by null ("\n\0"). description the browser allocates and initializes the npstream object and passes it to the plug-in in as a parameter to npp_newstream or npn_newstream. the browse...
NP_Initialize - Archive of obsolete content
etscapefuncs *anpnfuncs) unix #include <npapi.h> nperror np_initialize(npnetscapefuncs *anpnfuncs, nppluginfuncs *anppfuncs) 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 this function only once: when a plug-in is loaded, before the first instance is created. this is the first function that the browser calls. np_initialize tells the plug-in that the browser has loaded it and provides global initialization. allocate any memory or resources shared by all instances of your plug-in at this time. after the last instance of a plug-in has been deleted, the browser calls np_shutdown, where you can release allocated memory or re...
NP_Port - Archive of obsolete content
hich is allocated by the browser. the np_port is valid for the lifetime of the npwindow, that is, until npp_setwindow is called again with a different value or the instance is destroyed. since the port is shared between the plug-in and other plug-ins and the browser, the plug-in should always do the following: draw only within the area designated by the npwindow. save the current port settings before changing the port for drawing. set the desired port settings before drawing. restore the previous port settings after drawing. see also npp_setwindow, npwindow ...
NP_Shutdown - Archive of obsolete content
« gecko plugin api reference « plug-in side plug-in api summary provides global deinitialization for a plug-in. syntax #include <npapi.h> void np_shutdown(void); windows #include <npapi.h> void winapi np_shutdown(void); description the browser calls this function once after the last instance of your plug-in is destroyed, before unloading the plug-in library itself. use np_shutdown to delete any data allocated in np_initialize to be shared by all instances of a plug-in. if you have defined a java class for your plug-in, be sure to release it at this time so that java can unload it and free up memory. note: if enough memory is available, the browser can keep the plug-in library loaded if it expects to create more instances in the near future. the browser calls np_shutdown ...
Shipping a plugin as a Toolkit bundle - Archive of obsolete content
em:maxversion>4.0.*</em:maxversion> </description> </em:targetapplication> <em:unpack>true</em:unpack> </description> </rdf> this contains 5 required pieces of information. every add-on must have a unique id. this can be in a guid form but the simpler email form is preferred now. you should aim to use a domain-name that you own and then your own unique short-name for the plugin before the @. the plugin must have a name to identify the plugin to the user in the list of add-ons. the version is fairly self-descriptive, it must be a toolkit version format. the target application block says which versions of an application the plugin is compatible with. it includes the application id and the minimum and maximum version of the application that the plugin works with. there can be ...
The First Install Problem - Archive of obsolete content
this is an old working document; see en/gecko_plugin_api_reference/plug-in_development_overview for current information. problem definition the first install problem is the name given to the conditions arising when a plugin or embeddable software installs itself on a system first, before any other gecko-based browser. if this happens, gecko-based browsers often won't be able to discover the plugin, and will prompt the user to download the plugin again if the affiliated mime type is encountered on the web. unless gecko does a pre-emptive scan upon startup for desirable plugins that are not in the browser's plugins directory first, the best way to solve this problem is to encourage plugin vendors to leave dlls (and xpt files, if applicable) in a location that gecko can discover at runt...
Writing a plugin for Mac OS X - Archive of obsolete content
the sample is posted under a bsd-style license that means you can use it for anything, even if you don't plan to release your source code. getting started if you check out the mozilla source code in mac os x, you can simply open basicplugin.xcodeproj in xcode, click build, and you're done. xcode will create a "build" directory next to the project file, and if you built it in release mode, that folder in turn contains a "release" directory with the plugin inside it. ...
XEmbed Extension for Mozilla Plugins - Archive of obsolete content
t. since the gtkplug is just a container, you can add your own widgets at your leisure with the packing you prefer. telling mozilla you support xembed as mentioned above, you will need to tell mozilla that you support the xembed protocol for hosting plugins. for backwards compatibility reasons if you don't tell mozilla that you support it it will try to hand you an xt widget as a parent. however, before you do so you should make sure that the browser also supports xembed when the plugin is first initialized. if you've built your plugin so that it will support either xt or xembed you can include a fallback for older style hosting. if you haven't you can return an error and the plugin will be ignored. it's good practice to do this in case people try to install your plugin for older versions of the...
Plugins - Archive of obsolete content
this article explains how javascript can be used to access methods from within the flash plugin, as well as how a feature called fscommands can be used to access javascript functions from within the flash animation. plugins: the first install problem the first install problem is the name given to the conditions arising when a plugin or embeddable software installs itself on a system first, before any other gecko-based browser. plugins: samples and test cases npapi plugin samples and test cases. external resources for plugin creation external projects, frameworks, and blog posts that may be useful. xembed extension for mozilla plugins recent versions of mozilla on *nix-based systems include an extension for writing plugins that use xembed instead of using the old xt-based main ...
Why RSS Slash is Popular - Counting Your Comments - Archive of obsolete content
slashdot is one of the most popular blogs on the internet. with its own history and culture, it's responsible for the "first post!" phenomena, the anonymous coward, and the recognition of the slashdot effect, a phenomena that adorns its name. one of the quirks of slashdot is that it includes a comments count, a humorous department, a hit parade, and a section with every blog post. rss does not have any facilites for including this information in an <item>, so the rss slash module exists to fill in this gap. ...
Getting Started - Archive of obsolete content
ofmarkup . in other words, code like this doesn't bother you: this is some markup with <b>bold</b> tags. if you are comfortable with that, you should have no problem learning rss. note: if you are not a web developer and do not want to become one, then this tutorial is not for you. you need to be comfortable with creatingmarkup to be able to effectively use this tutorial. what do you need before you start? to get the most from this tutorial, you will need a text editor and a rss reader. you must also know how to use each of these. note: a word processor is not a text editor. if a word processor is used, you must make sure to save your rss files in a (pure and plain) text format. it is not mandatory to create rss files in this tutorial (you can just read on), but this would be a less...
.htaccess ( hypertext access ) - Archive of obsolete content
ditor, like windows notepad, vin, sublime text editor or any other. syntax highliting support for .htaccess files less. common application url redirects & rewrite: htaccess files are often used to redirect traffic to a web page to another or from traffic to a directory to another even between domains is possible. it's a fast and efficient way of redirecting traffic, because the redirect happens before the pages are served. redirects can be made on a temporary basis or permanently by supplying the status codes. redirect 301 / http://example.com/ # redirect the traffic to the directory to example.com , permanent redirect redirect 302 / http://example.com/ # redirect the traffic to the directory to example.com , temporary redirect blocking : htaccess also facilitates blocking traff...
Vulnerabilities - Archive of obsolete content
uration issues are also unavoidable for two reasons. first, many configuration settings increase security at the expense of reducing functionality, so using the most secure settings could make the software useless or unusable. second, many security settings have both positive and negative consequences for security. an example is the number of consecutive failed authentication attempts to permit before locking out a user account. setting this to 1 would be the most secure setting against password guessing attacks, but it would also cause legitimate users to be locked out after mistyping a password once, and it would also permit attackers to perform denial-of-service attacks against users more easily by generating a single failed login attempt for each user account. because of the number of vul...
Table Reflow Internals - Archive of obsolete content
with itself as the target. style changes through the dom - javascript, browser change font (ctrl+/-), a preference changes, etc. review of reflow reflow starts with pres shell which reflows the reflow root (usually the viewport frame), which reflows it children, etc. ususally it starts when the pres shell processes its queue of reflow commands. the reflower positions reflowee (if it can) before actually reflowing in case views are involved (e.g. absolutely positioned elements) reflows reflowee and passes a reflow state (in) and a reflow metrics (in/out) review of reflow the reflow state: is a node in a tree structurally equivalent to the frame tree of reflow participants contains: reflow type, avail size, various computed values, resolved style structs possible request for preferr...
The Basics of Web Services - Archive of obsolete content
s, so both the server and the client can understand each other. (xml introduction). a better way to understand a web service is to compare it to a html form communication with a server side script (such as php or asp) to post and send data. both web services and forms send and receive requests. the only major difference is that a web service uses xml. examples of web services in action as said before, rss and atom feeds are a simple example of how a web service works, most commonly, xml-rpc or soap are also used to communicate between a server and a client. introducing xml-rpc xml-rpc is a type of web service and has been around since 1998, though not an official w3c standard, it is widely used. xml-rpc was developed by useful inc, along with microsoft. warning: xml-rpc support was removed...
Common Firefox theme issues and solutions - Archive of obsolete content
ransition firefox no longer supports -moz-transition style property. use css standard transition property instead (supported by firefox since firefox 4). resources amo editors theme testing guidelines when developing and testing your themes, please refer to the theme testing guidelines amo editors use to review themes. this guide will help you thoroughly test your theme to find and fix issues before you push updates to amo. this is document is a work in progress so feedback and/or suggestions is appreciated. mdn css reference mozilla's developer network maintains a great css reference. amo themes forum we'd like to encourage you to participate in the amo (addons.mozilla.org) forums theme forum. mozillazine themes forum mozillazine is not an official mozilla website, but it does have t...
Theme changes in Firefox 2 - Archive of obsolete content
s this is a new file for firefox 2. it skins the firefox about box, and needs to provide at least the following styles: #aboutlogocontainer #aboutpagecontainer #version the default theme also skins the following styles: body, html, img, ul, and ul > li. ...
Theme changes in Firefox 3.5 - Archive of obsolete content
inimum size on mac os x. if your theme uses native checkboxes or radiobuttons (-moz-appearance: radio / checkbox), this can result in distorted controls. you might have to set the width and height of .checkbox-check and .radio-check to 16px to avoid that problem. look at the patch to see what was changed for pinstripe. bug 450944 changed the way window shadow is handled on mac os x. before that change, opaque windows always had a shadow and transparent windows never had a shadow. after that change, transparent windows also have a shadow by default. this can result in unwanted shadows in your theme, e.g. under the autoscroll icon or the identity panel. if you don't want the shadow, you can turn it off by setting the new -moz-window-shadow css property to none on the affected element...
Using SSH to connect to CVS - Archive of obsolete content
's probably easiest to start it up whenever you set up your environment to checkout and build mozilla. assuming you use a shell script or batch file to set things up, just add the commands below to the end of your file. posix shell eval `ssh-agent -s` ssh-add ~/.ssh/id_dsa $shell ssh-agent -k exit x windows in "~/.xinitrc" add "ssh-add". this will bring up a graphic box just after login, and before the desktop loads, asking for your passphrase. the passphrase will be held for the length of the x session, and be passed on to all child shells. ms-dos command prompt cygwin for /f "tokens=1,2,3* delims=; " %%a in ('ssh-agent -c') do if "%%a"=="setenv" set %%b=%%c set home=/cygdrive/c/path/to/your/cygwin/home/directory ssh-add ~/.ssh/id_dsa start /b /wait cmd.exe ssh-agent -k exit essential...
Using the W3C DOM - Archive of obsolete content
internet explorer's document.all[], that are not part of the w3c document object model (dom) standards and may cause javascript errors in standards-compliant browsers. the w3c document object model provides interfaces dom elements to scriptable objects. w3c dom standards are well supported by modern browsers, however the standards are moving target so support for newer features should be tested before use. using w3c standards means that code will run in compliant browsers with minimal need for cross-browser support, whereas code based on proprietary standards requires much more effort to be compatible with multiple user agents. unsupported dom-related properties the following ie proprietary document object properties are not supported in the w3c document object model: document.layers[] i...
-ms-wrap-flow - Archive of obsolete content
is created; for all other elements, an exclusion is not created. both inline flow content can flow on all sides of the exclusion. start inline flow content can wrap on the start edge of the exclusion area but must leave empty the area after the end edge of the exclusion area. end inline flow content can wrap after the end edge of the exclusion area but must leave empty the area before the start edge of the exclusion area. maximum inline flow content can wrap on the side of the exclusion with the largest available space for the given line, and must leave empty the other side of the exclusion. clear inline flow content can only wrap on top and bottom of the exclusion and must leave empty the areas to the start and end edges of the exclusion box. formal syntax au...
::-ms-browse - Archive of obsolete content
...
::-ms-check - Archive of obsolete content
...
::-ms-fill-lower - Archive of obsolete content
...
::-ms-fill-upper - Archive of obsolete content
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-ticks-after - Archive of obsolete content
the ::-ms-ticks-after css pseudo-element is a microsoft extension that applies one or more styles to the tick marks that appear after the track of a slider control. a slider control is one possible representation of <input type="range">. these ticks are not shown by default. to show them, set the control's display property to block. it is possible to use the ::-ms-ticks-after, ::-ms-ticks-before, and ::-ms-track pseudo-elements together. to do so would create three sets of tick marks, but the best user experience is one set. to remove tick marks altogether, set the color property to transparent. allowable properties only the following css properties can be used in a rule with ::-ms-ticks-after in its selector. other properties are ignored. background-clip background-color backgrou...
::-ms-track - Archive of obsolete content
the ::-ms-track css pseudo-element is a microsoft extension that represents the track of a slider control. a slider control is one possible representation of <input type="range">. applying the color property within the ::-ms-track selector affects the tick marks inside the track area. it is possible to use the ::-ms-ticks-after, ::-ms-ticks-before, and ::-ms-track pseudo-elements together. to do so would create three sets of tick marks, but the best user experience is one set. to remove tick marks altogether, set the color property to transparent. allowable properties only the following css properties can be used in a rule with ::-ms-track in its selector. other properties are ignored. background-clip background-color background-image background-origin background-repeat backgro...
Displaying notifications (deprecated) - Archive of obsolete content
.moznotification object's createnotification() method, as follows: var notification = navigator.moznotification.createnotification( "hey, check this out!", "this is a notification posted by " + "firefox 4. you should take some action. right now!"); this returns a new notification object, but does not actually display the notification. this lets you configure the event listeners before the notification is shown, if you need to be notified when the notification is dismissed. setting up event listeners on the notification there are two events you can listen to on created notifications: onclick this event is fired when the user clicks (or taps) on the notification. onclose this event is fired when the notification is closed (whether by being clicked or by some other means)...
Array.observe() - Archive of obsolete content
g argument: changes an array of objects each representing a change. the properties of these change objects are: name: the name of the property which was changed. object: the changed array after the change was made. type: a string indicating the type of change taking place. one of "add", "update", "delete", or "splice". oldvalue: only for "update" and "delete" types. the value before the change. index: only for the "splice" type. the index at which the change occurred. removed: only for the "splice" type. an array of the removed elements. addedcount: only for the "splice" type. the number of elements added. description the callback function is called each time a change is made to arr, with an array of all changes in the order in which they occurred. ch...
VBArray - Archive of obsolete content
icrosoft extension and is only supported in internet explorer. the vbarray object provides access to visual basic safe arrays. syntax varname = new vbarray(safearray) parameters varname the variable name to which the vbarray is assigned. safearray a vbarray value. remarks vbarrays are read-only, and cannot be created directly. the safearray argument must have obtained a vbarray value before being passed to the vbarray constructor. this can only be done by retrieving the value from an existing activex or other object. vbarrays can have multiple dimensions. the indices of each dimension can be different. the dimensions method retrieves the number of dimensions in the array; the lbound and ubound methods retrieve the range of indices used by each dimension. example the following exa...
@if - Archive of obsolete content
ers text1 optional text to be parsed if condition1 is true. text2 optional text to be parsed if condition1 is false and condition2 is true. text3 optional text to be parsed if both condition1 and condition2 are false. remarks when you write an @if statement, you do not have to place each clause on a separate line. you can use multiple @elif clauses. however, all @elif clauses must come before an @elseclause. the @if statement is typically used to determine which text among several options should be used for text output. it is not common to use conditional compilation variables in scripts written for asp or asp.net pages or command-line programs. this is because the capabilities of the compilers can be determined by using other methods. when you write a script for a web page, always...
@set - Archive of obsolete content
on statements, but can be used anywhere in javascript code. examples of variable declarations look like this: @set @myvar1 = 12 @set @myvar2 = (@myvar1 * 20) @set @myvar3 = @_jscript_version the following operators are supported in parenthesized expressions: ! ~ * / % + - << >> >>> < <= > >= == != === !== & ^ | && | | if a variable is used before it has been defined, its value is nan. nan can be checked for using the @if statement: @if (@newvar != @newvar) ... this works because nan is the only value not equal to itself. requirements supported in all versions of internet explorer, but not in windows 8.x store apps. see also conditional compilation conditional compilation variables @cc_on statement @if statement ...
Object.observe() - Archive of obsolete content
following argument: changes an array of objects each representing a change. the properties of these change objects are: name: the name of the property which was changed. object: the changed object after the change was made. type: a string indicating the type of change taking place. one of "add", "update", or "delete". oldvalue: only for "update" and "delete" types. the value before the change. acceptlist the list of types of changes to be observed on the given object for the given callback. if omitted, the array ["add", "update", "delete", "reconfigure", "setprototype", "preventextensions"] will be used. return value the object to be observed. description callback is called each time a change is made to obj, with an array of all changes in the order in whic...
JavaClass - Archive of obsolete content
vapackage object is a reference to a java package, such as netscape.javascript. in javascript, the javapackage and javaclass hierarchy reflect the java package and class hierarchy. you can pass a javaclass object to a java method which requires an argument of type java.lang.class. backward compatibility javascript 1.3 and earlier you must create a wrapper 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. examples example: using javaclass in the following example, x is a javaclass object refer...
Sharp variables in JavaScript - Archive of obsolete content
ber 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 sure you don't put in any spaces before the equal sign though. #1 = {}; // this doesn't do much since the sharp variable is out of scope immediately after a = #2 = {}; // slightly more useful since we retain a reference to the new object to reference the sharp variable, simply append another sharp (#) to the end of the variable name. this acts as a reference to initial variable. you can use this to create objects in a single ...
XForms Custom Controls - Archive of obsolete content
te implementation bindings that will inherit from these base bindings. for example, every output control implementation extends the base binding xforms.xml#xformswidget-output-base. the xhtml-specific pieces of our implementation of output is kept in the xforms-xhtml.xml#xformswidget-output binding. if you would like to do this kind of heroic work then please contact the mozilla xforms developers before you start. hopefully we can help you avoid a lot of frustration and despair :). overview the mozilla xforms controls are largely implemented using xbl and the bindings are applied to the individual xforms control tags via css. so you can always refer to our source code to get some great examples of how xforms controls can be written. this will also allow you to be up to date with our current appr...
Requests For Enhancement - Archive of obsolete content
Archive › Web › XForms › RFE
e. the xforms team looks at votes to help determine which bug is more important for our xforms users. rfe categories xforms api this section contains rfe to the xforms api. custom controls i think that xforms is a great way to show that 14 year old html hacks can build really powerful web apps and reduce the need for javascript by 90%. now we need to start teaching xforms to web newcomers before they are brainwashed into believing that the only way to build cool web apps is to do dom surgery with javascript! dan mccreary. one 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 ...
Using XForms and PHP - Archive of obsolete content
data to either serve a page (with xforms in it) or to generate data used as instance data for xforms, the page needs to be served as xml, for example application/xhtml+xml. to do that, you need to use the header() php function: <?php header("content-type: application/xhtml+xml; charset=utf-8"); ... ?> but remember this (quote from php documentation): remember that header() must be called before any actual output is sent, either by normal html tags, blank lines in a file, or from php. it is a very common error to read code with include(), or require(), functions, or another file access function, and have spaces or empty lines that are output before header() is called. the same problem exists when using a single php/html file. parsing submitted data depending on the submission type, y...
Displaying a graphic with audio samples - Archive of obsolete content
event.time, /* unused, but it's there */ signal = new float32array(fb.length / channels), magnitude; for (var i = 0, fbl = framebufferlength / 2; i < fbl; i++ ) { // assuming interlaced stereo channels, // need to split and merge into a stero-mix mono signal signal[i] = (fb[2*i] + fb[2*i+1]) / 2; } // clear the canvas before drawing spectrum ctx.fillstyle = "rgb(0,0,0)"; ctx.fillrect (0,0, canvas.width, canvas.height); ctx.fillstyle = "rgb(255,255,255)"; for (var i = 0; i < signal.length; i++ ) { // multiply spectrum by a zoom value magnitude = signal[i] * 1000; // draw rectangle bars for each frequency bin ctx.fillrect(i * 4, canvas.height, ...
Fixing Incorrectly Sized List Item Markers - Archive of obsolete content
summary: an obscure bug in gecko causes list-item markers to be differently sizeed than the text of the list item, but there is a fix authors can use. learn how to correctly size list item markers in gecko 0.9.4, the basis of netscape 6.2.x and compuserve 7. shortly before mozilla 0.9.4 was finished, a bug was introduced that affects the sizing of list item markers (such as the numbers in an ordered list). while this bug 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 ...
RDF in Mozilla FAQ - Archive of obsolete content
builder properties to get installed, but leaves the database empty of datasources: you've got to add these in yourself! can i manipulate a xul template using the dom apis? yes: you can add rules, remove rules, change a query, and change the content that is built by a rule. in fact, you can change anything about a template using the w3c dom apis. the only caveat is that you must call rebuild() before the changes you've made will take effect (just as you must if you add a datasource to the xul template). how do i insert plaintext from a template? to insert plaintext in a template, use the <text> element. <template> <rule> <query>...</query> <binding>...</binding> <action> <text value="?some-variable" /> </action> </rule> </template> the above template will create...
Windows Media in Netscape - Archive of obsolete content
examples in this article all assume that the user is running windows media player 7 and later, although netscape 7.1 supports the clsids of windows media player 6x and later. it is important to note that in netscape 7.1, only the classid for windows media player is supported, and no other control can be created. the various param elements that can be used and the functio...
XUL Parser in Python - Archive of obsolete content
d thing i have to open up. if you want to test this script you should change the filename "res.html" specified in the fourth line and compare different results files. note also that i wrote the build number into the header myself, and haven't figured out yet how to get that written automatically. i guess you could get a modify date from the files as you open them. how the script works as i said before, there isn't too much to explain in this script, particularly if you have used python's xmllib parser before. at the middle of it is a subclass of the xmllib parser that overrides that parser's unknown_starttag method and asks it to do all the work. the unknown_starttag handler is fed the tag name, the attributes of that tag, and the attributes' values, so all you have to do as you hit each xul e...
Archive of obsolete content
ry to keep the subpages here organized instead of all dumped into one large folder. try to create subtrees for categories of material. also, only move pages here that are extremely obsolete. if anyone might realistically need the information in a living product, it may not be appropriate to move it here. in general, it may be best to discuss it in the mdn web docs room on matrix before moving content here. .htaccess ( hypertext access ) file accessing : htaccess files can be opened using any text editor, like windows notepad, vin, sublime text editor or any other. syntax highliting support for .htaccess files less. 2015 mdn fellowship program add-ons archived add-ons documentation. adding prefere...
GLSL Shaders - Game development
ent that three.js will insert on the page to be the full size of the viewport. the <script> element in the <head> includes the three.js library in the page; we will write our code into three script tags in the <body> tag: the first one will contain the vertex shader. the second one will contain the fragment shader. the third one will contain the actual javascript code generating the scene. before reading on, copy this code to a new text file and save it in your working directory as index.html. we'll create a scene featuring a simple cube in this file to explain how the shaders work. the cube's source code instead of creating everything from scratch we can reuse the building up a basic demo with three.js source code of the cube. most of the components like the renderer, camera, and light...
Desktop gamepad controls - Game development
ontinuing it: if(gamepadapi.buttons.pressed('start')) { this.staterestart(); } if(gamepadapi.buttons.pressed('back')) { this.stateback(); } when the game over screen is visible, the start button restarts the game while the back button helps us get back to the main menu. the same goes for when the game is paused: the start button unpauses the game and the back button goes back, just like before. summary that's it! we have successfully implemented gamepad controls in our game — try connecting any popular controller like the xbox 360 one and see for yourself how fun it is to avoid the asteroids and shoot the aliens with a gamepad. now we can move on and explore new, even more unconventional ways to control the html5 game like waving your hand in front of the laptop or screaming into ...
Collision detection - Game development
bricks, let's add a status property to each brick object. update the following part of the code as indicated by the highlighted line: var bricks = []; for(var c=0; c<brickcolumncount; c++) { bricks[c] = []; for(var r=0; r<brickrowcount; r++) { bricks[c][r] = { x: 0, y: 0, status: 1 }; } } next we'll check the value of each brick's status property in the drawbricks() function before drawing it — if status is 1, then draw it, but if it's 0, then it was hit by the ball and we don't want it on the screen anymore. update your drawbricks() function as follows: function drawbricks() { for(var c=0; c<brickcolumncount; c++) { for(var r=0; r<brickrowcount; r++) { if(bricks[c][r].status == 1) { var brickx = (c*(brickwidth+brickpadding))+brick...
Finishing up - Game development
way it is being rendered. requestanimationframe helps the browser render the game better than the fixed framerate we currently have implemented using setinterval(). replace the following line: var interval = setinterval(draw, 10); with simply: draw(); and remove each instance of: clearinterval(interval); // needed for chrome to end game then, at the very bottom of the draw() function (just before the closing curly brace), add in the following line, which causes the draw() function to call itself over and over again: requestanimationframe(draw); the draw() function is now getting executed again and again within a requestanimationframe() loop, but instead of the fixed 10 milliseconds frame rate, we are giving control of the framerate back to the browser. it will sync the framerate accordi...
Game over - Game development
> 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 bounces off just like you'd expect; if not then the game is over as before. compare your code here's the working code for you to compare yours against: exercise: make the ball move faster when it hits the paddle. next steps we're doing quite well so far and our game is starting to feel a lot more worth playing now you can lose! but it is still missing something. let's move on to the sixth chapter — build the brick field — and create some bricks for the bal...
Move the ball - Game development
. add the following two new lines indicated below to your draw() function: function draw() { ctx.beginpath(); ctx.arc(x, y, 10, 0, math.pi*2); ctx.fillstyle = "#0095dd"; ctx.fill(); ctx.closepath(); x += dx; y += dy; } save your code again and try it in your browser. this works ok, although it appears that the ball is leaving a trail behind it: clearing the canvas before each frame the ball is leaving a trail because we're painting a new circle on every frame without removing the previous one. don't worry, because there's a method to clear canvas content: clearrect(). this method takes four parameters: the x and y coordinates of the top left corner of a rectangle, and the x and y coordinates of the bottom right corner of a rectangle. the whole area covered by th...
Animations and tweens - Game development
date() as shown below: function update() { game.physics.arcade.collide(ball, paddle, ballhitpaddle); game.physics.arcade.collide(ball, bricks, ballhitbrick); paddle.x = game.input.x || game.world.width*0.5; } then we can create the ballhitpaddle() function (having ball and paddle as default parameters), playing the wobble animation when it is called. add the following function just before your closing </script> tag: function ballhitpaddle(ball, paddle) { ball.animations.play('wobble'); } the animation is played every time the ball hits the paddle. you can add the animations.play() call inside the ballhitbrick() function too, if you feel it would make the game look better. tweens whereas animations play external sprites sequentially, tweens smoothly animate properties of a...
Build the brick field - Game development
thub and save it in your /img directory. drawing the bricks we will place all the code for drawing the bricks inside an initbricks function to keep it separated from the rest of the code. add a call to initbricks at the end of the create() function: function create(){ // ... initbricks(); } now onto the function itself. add the initbricks() function at the end of our games code, just before the closing </script> tag, as shown below. to begin with we've included the brickinfo object, as this will come in handy very soon: function initbricks() { brickinfo = { width: 50, height: 20, count: { row: 3, col: 7 }, offset: { top: 50, left: 60 }, padding: 10 }; } this brickinfo ...
Collision detection - Game development
hysics.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 as the bottom of your code, just before the closing </script> tag, as follows: function ballhitbrick(ball, brick) { brick.kill(); } and that's it! reload your code and you should see the new collision detection working just as required. thanks to phaser there are two parameters passed to the function — the first one is the ball, which we explicitly defined in the collide method, and the second one is the single brick from the...
Extra lives - Game development
y set to false. making our text styling dry as you probably noticed we're using the same styling for all three texts: scoretext, livestext and lifelosttext. if we ever want to change the font size or color we will have to do it in multiple places. ...
Game over - Game development
« previousnext » this is the 8th 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/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. add the code below inside the create() function; just after you define the ball's attributes is fine: game.physics.arcade.checkcollision.down = false; this will make the three walls (top, left and right) bounce the ball back, but the fourth (bottom) will disappear, letting the ball ...
Initialize the framework - Game development
this can be done using html — the phaser framework will generate the required <canvas> element. ...
Move the ball - Game development
works: next steps the next step is to add some basic collision detection, so our ball can bounce off the walls. this would take several lines of code — a significantly more complex step than we have seen so far, especially if we want to add paddle and brick collisions too — but fortunately phaser allows us to do this much more easily than if we wanted to use pure javascript. in any case, before we do all that we will first introduce phaser's physics engines, and do some setup work. « previousnext » ...
2D maze game with device orientation - Game development
ll show the screen with the information on how to play the game. howto.js ball.howto = function(game) { }; ball.howto.prototype = { create: function() { this.buttoncontinue = this.add.button(0, 0, 'screen-howtoplay', this.startgame, this); }, startgame: function() { this.game.state.start('game'); } }; the howto state shows the gameplay instructions on the screen before starting the game. after clicking the screen the actual game is launched. game.js the game state from the game.js file is where all the magic happens. all the initialization is in the create() function (launched once at the beginning of the game). after that some functionality will require further code to control — we will write our own functions to handle more complicated tasks. in particula...
Boot2Gecko - MDN Web Docs Glossary: Definitions of Web-related terms
boot2gecko (b2g) is the engineering codename for firefox os and refers to builds that haven't yet received official firefox os branding. (firefox os was also often called boot2gecko before the project had an official name.) ...
Breadcrumb - MDN Web Docs Glossary: Definitions of Web-related terms
ed to get to the current page, in the order visited. a location breadcrumb for this document might look something like this: mdn > glossary > breadcrumb breadcrumb trails enable users to be aware of their location within a website. this type of navigation, if done correctly, helps users know where they are in a site and how they got there. they can also help a user get back to where they were before and can reduce the number of clicks needed to get to a higher-level page. ...
Cipher - MDN Web Docs Glossary: Definitions of Web-related terms
modern ciphers are designed to withstand attacks discovered by a cryptanalyst. there is no guarantee that all attack methods have been discovered, but each algorithm is judged against known classes of attacks. ...
Cipher suite - MDN Web Docs Glossary: Definitions of Web-related terms
a cipher suite is a combination of a key exchange algorithm, authentication method, bulk encryption cipher, and message authentication code. in a cryptosystem like tls, the client and server must agree on a cipher suite before they can begin communicating securely. a typical cipher suite looks like ecdhe_rsa_with_aes_128_gcm_sha256 or ecdhe-rsa-aes128-gcm-sha256, indicating: ecdhe (elliptic curve diffie-hellman ephemeral) for key exchange rsa for authentication aes-128 as the cipher, with galois/counter mode (gcm) as the block cipher mode of operation sha-256 as the hash-based message authentication code (hmac) learn more mozilla recommended cipher suite choices for tls ...
Gzip compression - MDN Web Docs Glossary: Definitions of Web-related terms
gzip is a file format used for file compression and decompression. it is based on the deflate algorithm that allows files to be made smaller in size which allows for faster network transfers. gzip is commonly supported by web servers and modern browsers, meaning that servers can automatically compress files with gzip before sending them, and browsers can uncompress files upon receiving them. learn more how to enable compression and gzip for page speed. gzip on wikipedia ...
Grid Lines - MDN Web Docs Glossary: Definitions of Web-related terms
when placing an item, you can then use these names instead of the line number, as demonstrated below. * {box-sizing: border-box;} .wrapper { border: 2px solid #f76707; border-radius: 5px; background-color: #fff4e6; display: grid; grid-template-columns: repeat(3, 1fr); grid-template-rows: repeat(3, 100px); } .wrapper > div { ...
Houdini - MDN Web Docs Glossary: Definitions of Web-related terms
bject model (cssom), enabling developers to write code the browser can parse as css. the benefit of houdini is that developers can create css features without waiting for web standards specifications to define them and without waiting for every browser to fully implement the features. while many of the features houdini enables can be created with javascript, interacting directly with the cssom before javascript is enabled provides for faster parse times. browsers create the cssom — including layout, paint, and composite processes — before applying any style updates found in scripts: layout, paint, and composite processes are repeated for updated javascript styles to be implemented. houdini code doesn't wait for that first rendering cycle to be complete. rather, it is included in that fir...
JSON - MDN Web Docs Glossary: Definitions of Web-related terms
pings) made up of these values (or of other arrays and objects). json does not natively represent more complex data types like functions, regular expressions, dates, and so on. (date objects by default serialize to a string containing the date in iso format, so the information isn't completely lost.) if you need json to represent additional data types, transform values as they are serialized or before they are deserialized. much like xml, json has the ability to store hierarchical data unlike the more traditional csv format. many tools provide translation between these formats such as this online json to csv converter or this alternative json to csv converter. learn more general knowledge json on wikipedia technical reference json on mdn ...
MVC - MDN Web Docs Glossary: Definitions of Web-related terms
ta 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 controller could handle this directly without needing to update the model. mvc on the web as a web developer, this pattern will probably be quite familiar even if you've never consciously used it before. your data model is probably contained in some kind of database (be it a traditional server-side database like mysql, or a client-side solution such as indexeddb [en-us].) your app's controlling code is probably written in html/javascript, and your user interface is probably written using html/css/whatever else you like. this sounds very much like mvc, but mvc makes these components follow a more...
MitM - MDN Web Docs Glossary: Definitions of Web-related terms
visible to you and to your recipient. in physical mail and in online communication, mitm attacks are tough to defend. a few tips: don't just ignore certificate warnings. you could be connecting to a phishing server or an imposter server. sensitive sites without https encryption on public wi-fi networks aren't trustworthy. check for https in your address bar and ensure encryption is in-place before logging in. learn more owasp article: man-in-the-middle attack wikipedia: man-in-the-middle attack the public-key-pins header (hpkp) can significantly decrease the risk of mitm by instructing browsers to require a whitelisted certificate for all subsequent connections to that website. ...
Opera Browser - MDN Web Docs Glossary: Definitions of Web-related terms
opera is the fifth most used web browser, publicly released in 1996 and initially running on windows only. opera uses blink as its layout engine since 2013 (before that, presto). opera also exists in mobile and tablet versions. learn more general knowledge opera browser on wikipedia opera browser web site ...
Packet - MDN Web Docs Glossary: Definitions of Web-related terms
occur when data is transmitted to the receiver. there are two types of error corrections backward and forward error correction. backward error correction is when the receiver requests the sender to retransmit the entire data unit. forward error correction is when the receiver uses the error-correcting code which automatically corrects the errors at the transmitter, the calculation is performed before the packet is sent. when received at the destination, the checksum is recalculated, and compared with the one in the packet. priority this field indicates which packet should have higher priority over the others. the high priority queue is emptied more quickly than lower priority queues when the network is congested. addresses when routing network packets it requires two ne...
Page prediction - MDN Web Docs Glossary: Definitions of Web-related terms
page prediction is a browser feature or script which, when enabled, tells the browser to download resources the user is likely to visit before the user requests the content. page prediction improves performance by enabling almost instant loading of predicted content. however, page prediction may also download content a user does not seek. some web applications include a prediction feature completing search text and address bar urls based on browsing history and related searches. for example, as the user types in the address bar, the browser might send the current text in the address bar to the search engine before the user submits the request. although browser page prediction and prediction services enable faster page loads, they consume additional bandwidth. also, pre-loaded websites ...
Preflight request - MDN Web Docs Glossary: Definitions of Web-related terms
ntrol-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. ...
Primitive - MDN Web Docs Glossary: Definitions of Web-related terms
5 did you expect it to be 7 instead of 5? if so, read how this code runs: for both the addtwo and addtwo_v2 functions calls, javascript looks up the value for the identifier foo. it correctly finds our variable instantiated with our first statement after finding it, the expression is evaluated, foo is replaced by 5 and the javascript engine passes that value to the functions as an argument before executing the statements inside the functions' bodies, javascript takes a copy of the originally passed argument (which is a primitive) and creates a local copy. these copies, existing only inside the functions' scopes, are accessible via the identifiers we specified in the functions' definitions (num for addtwo, foo for addtwo_v2) then, the functions' statements are executed: in the first...
SLD - MDN Web Docs Glossary: Definitions of Web-related terms
for example, in mozilla.org, mozilla is the second-level domain of the .org tld. a domain name is not limited to a tld and an sld. additional subdomains can be created in order to provide additional information about various functions of a server or to delimit areas under the same domain. for example, www is a commonly used subdomain to indicate the domain points to a web server. ...
SQL Injection - MDN Web Docs Glossary: Definitions of Web-related terms
sword 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 true, so authentication bypasses successfully. just due to a simple string (magical string) the entire database is compromised. how to prevent before executing the queries for the user credentials, make some changes like the following: $id = $_get['id'] (1) $id = stripslashes($id) (2) $id = mysql_real_escape_string($id) so due to (1) each single quote (') in the input string is replaced with double quotes ("), and due to (2) before every (') it adds (/). the revised magical string fails to bypass the authentication, and your database stay...
Second-level Domain - MDN Web Docs Glossary: Definitions of Web-related terms
for example, in mozilla.org, mozilla is the second level domain of the .org tld. a domain name is not limited to a tld and an sld. additional subdomains can be created in order to provide additional information about various functions of a server or to delimit areas under the same domain. for example, www is a commonly used subdomain to indicate the domain points to a web server. as another example, in developer.mozilla.org, the developer subdomain is used to specify that the subdomain contains the developer section of the mozilla website. ...
Smoke Test - MDN Web Docs Glossary: Definitions of Web-related terms
a smoke test consists of functional or unit tests of critical software functionality. smoke testing comes before further, in-depth testing. smoke testing answers questions like "does the program start up correctly?" "do the main control buttons function?" "can you save a simple blank new test user account?" if this basic functionality fails, there is no point investing time in more detailed qa work at this stage. learn more general knowledge smoke testing (software) on wikipedia ...
Specification - MDN Web Docs Glossary: Definitions of Web-related terms
in the context of describing the web, the term "specification" (often shortened to simply "spec") generally means a document describing a language, technology, or api which makes up the complete set of open web technologies. ...
TCP slow start - MDN Web Docs Glossary: Definitions of Web-related terms
ket transmission, and balances the speed of a network connection. it prevents the appearance of network congestion whose capabilities are initially unknown, and slowly increases the volume of information diffused until the network's maximum capacity is found. to implement tcp slow start, the congestion window (cwnd) sets an upper limit on the amount of data a source can transmit over the network before receiving an acknowledgment (ack). the slow start threshold (ssthresh) determines the (de)activation of slow start. when a new connection is made, cwnd is initialized to one tcp data or acknowledgment packet, and waits for an acknowledgement, or ack. when that ack is received, the congestion window is incremented until the cwnd is less than ssthresh. slow start also terminates when congestion is ...
TTL - MDN Web Docs Glossary: Definitions of Web-related terms
it provides a way to avoids network congestion, but releasing packets after they roamed the network too long. caching in the context of caching, ttl (as an unsigned 32-bit integer) being a part of the http response header or the dns query, indicates the amount of time in seconds during which the ressource can be cached by the requester. ...
Transmission Control Protocol (TCP) - MDN Web Docs Glossary: Definitions of Web-related terms
...
Unicode - MDN Web Docs Glossary: Definitions of Web-related terms
unicode is a standard character set that numbers and defines characters from the world's different languages, writing systems, and symbols. by assigning each character a number, programmers can create character encodings, to let computers store, process, and transmit any combination of languages in the same file or program. before unicode, it was difficult and error-prone to mix languages in the same data. for example, one character set would store japanese characters, and another would store the arabic alphabet. if it was not clearly marked which parts of the data were in which character set, other programs and computers would display the text incorrectly, or damage it during processing. if you've ever seen text where characters like curly quotes (“”) were replaced with gibberish l...
Loop - MDN Web Docs Glossary: Definitions of Web-related terms
tions that is continually repeated until a certain condition is met in computer programming. an example would be the process of getting an item of data and changing it, and then making sure some condition is checked such as, if a counter has reached a prescribed number. examples for loop syntax: for (statement 1; statement 2; statement 3){ execute code block } statement 1 is executed once before the code block is run. statement 2 defines the condition needed to execute the code block. statement 3 is executed every time the code block is run. example: for(var i = 0; i < 10; i++){ console.log(i) } //this loop will print numbers 0-9, will stop when condition is met (i = 10) for the above example, the syntax is as follows: statement 1 sets the variable for the loop (var i = 0).
Strict mode - MDN Web Docs Glossary: Definitions of Web-related terms
...
CSS and JavaScript accessibility best practices - Learn web development
ever when you allow a non-default-focusable event to have focus using tabindex — in such cases you need to detect specifically when that exact key is pressed (see building keyboard accessibility back in). test your skills! you've reached the end of this article, but can you remember the most important information? you can find some further tests to verify that you've retained this information before you move on — see test your skills: css and javascript accessibility. summary we hope this article has given you a good amount of detail and understanding about the accessibility issues surrounding css and javascript use on web pages. next up, wai-aria! previous overview: accessibility next in this module what is accessibility? html: a good basis for accessibility css and jav...
Accessible multimedia - Learn web development
r('.fwd'); const timelabel = document.queryselector('.time'); next, we need to grab a reference to the video/audio player itself — add this line below the previous lines: const player = document.queryselector('video'); this holds a reference to a htmlmediaelement object, which has several useful properties and methods available on it that can be used to wire up functionality to our buttons. before moving onto creating our button functionality, let's remove the native controls so they don't get in the way of our custom controls. add the following, again at the bottom of your javascript: player.removeattribute('controls'); doing it this way round rather than just not including the controls attribute in the first place has the advantage that if our javascript fails for any reason, the user ...
Test your skills: WAI-ARIA - Learn web development
can you give the search input a suitable label, without explicitly adding a visible text label to the dom? try updating the live code below to recreate the finished example: download the starting point for this task to work in your own editor or in an online editor. wai-aria 3 for this final wai-aria task, we return to an example we previously saw in the css and javascript skilltest. as before, we have a simple app that presents a list of animal names. clicking one of the animal names causes a further description of that animal to appear in a box below the list. here, we are starting with a mouse- and keyboard-accessible version. the problem we have now is that when the dom changes to show a new decription, screenreaders cannot see what has changed. can you update it so that descrip...
A cool-looking box - Learn web development
objective: to test comprehension of the css box model and other box-related features such as borders and backgrounds. starting point to get this assessment started, you should: make local copies of the starting html and css — save them as index.html and style.css in a new directory. alternatively, you could use a site like jsbin or glitch to do your assessment. ...
Advanced styling effects - Learn web development
ws, 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 shadow, giving the appearance of the button being pressed in. note: there is another item that can be set in the box-shadow value — another length value can be optionally set just before the color value, which is a spread radius. if set, this causes the shadow to become bigger than the original box. it is not very commonly used, but worth mentioning. filters while you can't change the composure of an image using css, there are some creative things you can do. one very nice property, which can help you bring interest to your designs, is the filter property. this property enabl...
Backgrounds and borders - Learn web development
changed the values for the top right corner to make it different. you can play with the values to change the corners. take a look at the property page for border-radius to see the available syntax options. test your skills! we have covered a lot in this article, but can you remember the most important information? you can find some further tests to verify that you've retained this information before you move on — see test your skills: backgrounds and borders. summary we have covered quite a lot here, and you can see that there is quite a lot to adding a background or a border to a box. do explore the different property pages if you want to find out more about any of the features we have discussed. each page on mdn has more examples of usage for you to play with and enhance your knowledge...
Creating fancy letterheaded paper - Learn web development
objective: to test comprehension of css box model, and other box-related features such as implementing backgrounds. ...
Handling different text directions - Learn web development
sions. however, ultimately we expect that people will transition to the logical versions for most things, as they make a lot of sense once you start also dealing with layout methods such as flexbox and grid. test your skills! we have covered a lot in this article, but can you remember the most important information? you can find some further tests to verify that you've retained this information before you move on — see test your skills: writing modes. summary the concepts explained in this lesson are becoming increasingly important in css. an understanding of the block and inline direction — and how text flow changes with a change in writing mode — will be very useful going forward. it will help you in understanding css even if you never use a writing mode other than a horizontal one. ...
Attribute selectors - Learn web development
tribute value which starts with a, so matches the first two list items. li[class$="a"] matches any attribute value that ends with a, so matches the first and third list item. li[class*="a"] matches any attribute value where a appears anywhere in the string, so it matches all of our list items. case-sensitivity if you want to match attribute values case-insensitively you can use the value i before the closing bracket. this flag tells the browser to match ascii characters case-insensitively. without the flag the values will be matched according to the case-sensitivity of the document language — in html's case it will be case sensitive. in the example below, the first selector will match a value that begins with a — it only matches the first list item because the other two list items st...
Combinators - Learn web development
in question. that said, your knowledge of combinators will come in very useful if you need to get to something in your document and are unable to access the html, perhaps due to it being generated by a cms. test your skills! we have covered a lot in this article, but can you remember the most important information? you can find some further tests to verify that you've retained this information before you move on — see test your skills: selectors. moving on this is the last section in our lessons on selectors. next we will move on to another important part of css — the css box model. previous overview: building blocks next in this module cascade and inheritance css selectors type, class, and id selectors attribute selectors pseudo-classes and pseudo-elements ...
CSS selectors - Learn web development
bined into a selector list so that the rule is applied to all of the individual selectors. for example, if i have the same css for an h1 and also a class of .special, i could write this as two separate rules. h1 { color: blue; } .special { color: blue; } i could also combine these into a selector list, by adding a comma between them. h1, .special { color: blue; } white space is valid before or after the comma. you may also find the selectors more readable if each is on a new line. h1, .special { color: blue; } in the live example below try combining the two selectors which have identical declarations. the visual display should be the same after combining them. when you group selectors in this way, if any selector is invalid the whole rule will be ignored. in the following ...
CSS values and units - Learn web development
side your css. it's particularly useful if you want to work out values that you can't define when writing the css for your project, and need the browser to work out for you at runtime. for example, below we are using calc() to make the box 20% + 100px wide. the 20% is calculated from the width of the parent container .wrapper and so will change if that width changes. we can't do this calculation beforehand because we don't know what 20% of the parent will be, so we use calc() to tell the browser to do it for us. test your skills! we have covered a lot in this article, but can you remember the most important information? you can find some further tests to verify that you've retained this information before you move on — see test your skills: values and units. summary this has been a quic...
CSS building blocks - Learn web development
with the language and its syntax, and got some basic experience with using it, its time to dive a bit deeper. this module looks at the cascade and inheritance, all the selector types we have available, units, sizing, styling backgrounds and borders, debugging, and lots more. the aim here is to provide you with a toolkit for writing competent css and help you understand all the essential theory, before moving on to more specific disciplines like text styling and css layout. looking to become a front-end web developer? we have put together a course that includes all the essential information you need to work towards your goal. get started prerequisites before starting this module, you should have: basic familiarity with using computers, and using the web passively (i.e. just looking a...
Beginner's guide to media queries - Learn web development
up a section about media queries with a suggestion that you might not need one at all! however, in practice you will find that good use of modern layout methods, enhanced with media queries, will give the best results. test your skills! you've reached the end of this article, but can you remember the most important information? you can find a test to verify that you've retained this information before you move on — see test your skills: responsive web design. summary in this lesson you have learned about media queries, and also discovered how to use them in practice to create a mobile first responsive design. you could use the starting point that we have created to test out more media queries. for example, perhaps you could change the size of the navigation if you detect that the visitor ...
Multiple-column layout - Learn web development
summary you now know how to use the basic features of multiple-column layout, another tool at your disposal when choosing a layout method for the designs you are building. ...
Practical positioning examples - Learn web development
get an idea of what you will be building in this section of the article. as a starting point, you can use your completed example from the first section of the article, or make a local copy of info-box.html from our github repo. html additions first of all, we need some additional html to represent the web site main content. add the following <section> just below your opening <body> tag, just before the existing section: <section class="fake-content"> <h1>fake content</h1> <p>this is fake content. your main web page contents would probably go here.</p> <p>this is fake content. your main web page contents would probably go here.</p> <p>this is fake content. your main web page contents would probably go here.</p> <p>this is fake content. your main web page contents would probably go...
Responsive design - Learn web development
had to be developed and kept up-to-date. in addition, these mobile sites often offered a very cut down experience. as mobile devices became more powerful and able to display full websites, this was frustrating to mobile users who found themselves trapped in the site's mobile version and unable to access information they knew was on the full-featured desktop version of the site. flexible layout before responsive design a number of approaches were developed to try to solve the downsides of the liquid or fixed-width methods of building websites. in 2004 cameron adams wrote a post entitled resolution dependent layout, describing a method of creating a design that could adapt to different screen resolutions. this approach required javascript to detect the screen resolution and load the correct cs...
Supporting older browsers - Learn web development
prerequisites: html basics (study introduction to html), and an idea of how css works (study introduction to css and styling boxes.) objective: to understand how to provide support for your layouts on older browsers that might not support the features you want to use. what is the browser landscape for your site? every website is different in terms of target audience. before deciding on the approach to take, find out the number of visitors coming to your site using older browsers. this is straightforward if you have an existing website which you are adding to or replacing, as you probably have analytics available which can tell you the technology people are using. if you have no analytics or this is a brand new site, then there are sites such as statcounter that can ...
Using your new knowledge - Learn web development
previous overview: first steps with the things you have learned in the last few lessons you should find that you can format simple text documents using css, to add your own style to them. this assessment gives you a chance to do that. prerequisites: before attempting this assessment you should have worked through the rest of the css basics module, and also have an understanding of html basics (study introduction to html). objective: to have a play with some css and test your new-found knowledge. starting point you can work in the live editor below, or you can download the starting point to work with in your own editor. this is a single page with the html, plus the starting point css in the head of the document. if you prefer you could move this css...
CSS first steps - Learn web development
decorative features. this module provides a gentle beginning to your path towards css mastery with the basics of how it works, what the syntax looks like, and how you can start using it to add styling to html. looking to become a front-end web developer? we have put together a course that includes all the essential information you need to work towards your goal. get started prerequisites before starting this module, you should have: basic familiarity with using computers, and using the web passively (i.e. looking at it, consuming the content.) a basic work environment set up as detailed in installing basic software, and an understanding of how to create and manage files, as detailed in dealing with files. basic familiarity with html, as discussed in the introduction to html module.
CSS FAQ - Learn web development
Learn › CSS › Howto › CSS FAQ
l will improve browser standards compliance. modern browsers have two main rendering modes: quirks mode: also called backwards-compatibility mode, allows legacy webpages to be rendered as their authors intended, following the non-standard rendering rules used by older browsers. documents with an incomplete, incorrect, or missing doctype declaration or a known doctype declaration in common use before 2001 will be rendered in quirks mode. standards mode: the browser attempts to follow the w3c standards strictly. new html pages are expected to be designed for standards-compliant browsers, and as a result, pages with a modern doctype declaration will be rendered with standards mode. gecko-based browsers, have a third almost standards mode that has only a few minor quirks. this is a list of t...
Typesetting a community school homepage - Learn web development
objective: to test comprehension of css text styling techniques. ...
Styling text - Learn web development
s including setting font, boldness, italics, line and letter spacing, drop shadows, and other text features. we round off the module by looking at applying custom fonts to your page, and styling lists and links. looking to become a front-end web developer? we have put together a course that includes all the essential information you need to work towards your goal. get started prerequisites before starting this module, you should already have basic familiarity with 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 su...
What text editors are available? - Learn web development
se the written documentation when you're learning how to use the editor. get in touch with other users if you're troubleshooting while installing or using the editor. does my text editor's look-and-feel matter to me? well, that's a matter of taste, but some people like customizing every bit of the ui (user interface), from colors to button positions. editors vary widely in flexibility, so check beforehand. it's not hard to find a text editor that can change color scheme, but if you want hefty customizing you may be better off with an ide. install and set up installing a text editor is usually quite straightforward. the method varies based on your platform but it shouldn't be too hard: windows. the developers will give you an .exe or .msi file. sometimes the software comes in a compressed ...
How do you host your website on Google App Engine? - Learn web development
te. here's a step-by-step guide to hosting your website on google app engine. creating a google cloud platform project to use google's tools for your own site or app, you need to create a new project on google cloud platform. this requires having a google account. go to the app engine dashboard on the google cloud platform console and press the create button. if you've not created a project before, you'll need to select whether you want to receive email updates or not, agree to the terms of service, and then you should be able to continue. enter a name for the project, edit your project id and note it down. for this tutorial, the following values are used: project name: gae sample site project id: gaesamplesite click the create button to create your project. creating an a...
How much does it cost to do something on the Web? - Learn web development
comprehensive you'll never use every feature. if at some point you need to exchange projects with other designers, you should find out what tools they're using. editors can all export finished projects to standard file formats, but each editor saves ongoing projects in its own specialized format. most of the images on the internet are copyrighted, so it is better to check the license of the file before you use it. sites like pixabay provide images under cc0 license, so you can use, edit and publish them even with modification for commercial use. media editors if you want to include video or audio into your website, you can either embed online services (for example youtube, vimeo, or dailymotion), or include your own videos (see below for bandwidth costs). for audio files, you can find free s...
What are browser developer tools? - Learn web development
every modern web browser includes a powerful suite of developer tools. these tools do a range of things, from inspecting currently-loaded html, css and javascript to showing which assets the page has requested and how long they took to load. this article explains how to use the basic functions of your browser's devtools. note: before you run through the examples below, open the beginner's example site that we built during the getting started with the web article series. you should have this open as you follow the steps below. how to open the devtools in your browser the devtools live inside your browser in a subwindow that looks roughly like this, depending on what browser you are using: how do you pull it up? three ways: keyboard: ctrl + shift + i, except internet explorer ...
What are hyperlinks? - Learn web development
allowing for embedded hyperlinks as you can see in the three pillars, everything on the web revolves around documents and how to access them. the web's original purpose was to provide an easy way to reach, read, and navigate through text documents. since then, the web has evolved to provide access to images, videos, and binary data, but these improvements have hardly changed the three pillars. before the web, it was quite hard to access documents and move from one to another. being human-readable, urls already made things easier, but it's hard to type a long url whenever you want to access a document. this is where hyperlinks revolutionized everything. links can correlate any text string with a url, such that the user can instantly reach the target document by activating the link. links stan...
What is a web server? - Learn web development
web server. a static web server, or stack, consists of a computer (hardware) with an http server (software). we call it "static" because the server sends its hosted files as-is to your browser. a dynamic web server consists of a static web server plus extra software, most commonly an application server and a database. we call it "dynamic" because the application server updates the hosted files before sending content to your browser via the http server. for example, to produce the final webpages you see in the browser, the application server might fill an html template with content from a database. sites like mdn or wikipedia have thousands of webpages. typically, these kinds of sites are composed of only a few html templates and a giant database, rather than thousands of static html document...
Sending form data - Learn web development
to access the data sent with the post method by name // to access the data sent with the get method, you can use $_get $say = htmlspecialchars($_post['say']); $to = htmlspecialchars($_post['to']); echo $say, ' ', $to; ?> this example displays a page with the data we sent. you can see this in action in our example php-example.html file — which contains the same example form as we saw before, with a method of post and an action of php-example.php. when it is submitted, it sends the form data to php-example.php, which contains the php code seen in the above block. when this code is executed, the output in the browser is hi mom. note: this example won't work when you load it into a browser locally — browsers cannnot interpret php code, so when the form is submitted the browser wi...
Test your skills: Form validation - Learn web development
r code in an online tool such as codepen, jsfiddle, or glitch to work on the tasks. if you get stuck, then ask us for help — see the assessment or further help section at the bottom of this page. form validation 1 in this task, we are providing you with a simple support query form, and we want you to add some validation features to it: make all of the input fields mandatory to complete before the form can be submitted. change the type of the "email address" and "phone 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 submitt...
Dealing with files - Learn web development
previous overview: getting started with the web next 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 on your local computer, make sure they can talk to one another, and get all your content looking right before you eventually upload them to a server. dealing with files discusses some issues you should be aware of so you can set up a sensible file structure for your website. where should your website live on your computer? when you are working on a website locally on your computer, you should keep all the related files in a single folder that mirrors the published website's file structure on the server. this folder can live anywhere you like, but yo...
Installing basic software - Learn web development
r your favorite browsers: linux: firefox, chrome, opera, brave. windows: firefox, chrome, opera, internet explorer, microsoft edge, brave (windows 10 comes with edge by default; if you have windows 7 or above, you can install internet explorer 11; otherwise, you should install an alternative browser). macos: firefox, chrome, opera, safari, brave (macos and ios come with safari by default). before going on, you should install at least two of these browsers and have them ready for testing. note: internet explorer is not compatible with some modern web features and it may not be able to run your project. you usually don't need to worry about making your web projects compatible with it, as very few people still use it — certainly don't worry too much about it while you are learning. you m...
Getting started with the Web - Learn web development
ney! 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 the software you need to begin some basic web development. what will your website look like? before you start writing the code for your website, you should plan it first. what information are you showcasing? what fonts and colors are you using? what will your website look like? we outline a simple method you can follow to plan out your site's content and design. dealing with files a website consists of many files: text content, code, stylesheets, media content, and so on. when you're building...
Using data attributes - Learn web development
dataset.parent // "cars" each property is a string and can be read and written. in the above case setting article.dataset.columns = 5 would change that attribute to "5". css access note that, as data attributes are plain html attributes, you can even access them from css. for example to show the parent data on the article you can use generated content in css with the attr() function: article::before { content: attr(data-parent); } you can also 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 ...
Advanced text formatting - Learn web development
summary that marks the end of our study of html text semantics. bear in mind that what you have seen during this course is not an exhaustive list of html text elements — we wanted to try to cover the essentials, and some of the more common ones you will see in the wild, or at least might find interesting. to find way more html elements...
Debugging HTML - Learn web development
en simple cases can look a little intimidating to someone who doesn't know anything about rust. debugging doesn't have to be scary though — the key to being comfortable with writing and debugging any programming language or code is familiarity with both the language and the tools. html and debugging html is not as complicated to understand as rust. html is not compiled into a different form before the browser parses it and shows the result (it is interpreted, not compiled). and html's element syntax is arguably a lot easier to understand than a "real programming language" like rust, javascript, or python. the way that browsers parse html is a lot more permissive than how programming languages are run, which is both a good and a bad thing. permissive code so what do we mean by permissive?
Document and website structure - Learn web development
g like this: html for structuring content the simple example shown above isn't pretty, but it is perfectly fine for illustrating a typical website layout example. some websites have more columns, some are a lot more complex, but you get the idea. with the right css, you could use pretty much any elements to wrap around the different sections and get it looking how you wanted, but as discussed before, we need to respect semantics and use the right element for the right job. this is because visuals don't tell the whole story. we use color and font size to draw sighted users' attention to the most useful parts of the content, like the navigation menu and related links, but what about visually impaired people for example, who might not find concepts like "pink" and "large font" very useful? n...
Marking up a letter - Learn web development
previous overview: introduction to html next we all learn to write a letter sooner or later; it is also a useful example to test our text formatting skills. in this assignment, you'll have a letter to mark up as a test for your html text formatting skills, as well as hyperlinks and proper use of the html <head> element. prerequisites: before attempting this assessment you should have already worked through getting started with html, what's in the head? metadata in html, html text fundamentals, creating hyperlinks, and advanced text formatting. objective: test basic and advanced html text formatting, use of hyperlinks, and use of html <head>. starting point to begin, get the raw text you need to mark up, and the the css to style the html. create a new .
Structuring a page of content - Learn web development
previous overview: introduction to html structuring a page of content ready for laying it out using css is a very important skill to master, so in this assessment you'll be tested on your ability to think about how a page might end up looking, and choose appropriate structural semantics to build a layout on top of. prerequisites: before attempting this assessment you should have already worked through the rest of the course, with a particular emphasis on document and website structure. objective: to test knowledge of web page structures, and how to represent a prospective layout design in markup. starting point to get this assessment started, you should go and grab the zip file containing all the starting assets. the zip file contains: the html you ...
What’s in the head? Metadata in HTML - Learn web development
the path to the stylesheet file: <link rel="stylesheet" href="my-css-file.css"> the <script> element should also go into the head, and should include a src attribute containing the path to the javascript you want to load, and defer, which basically instructs the browser to load the javascript at the same time as the page's html. this is useful as it makes sure that the html is all loaded before the javascript runs, so that you don't get errors resulting from javascript trying to access an html element that doesn't exist on the page yet. there are actually a number of ways to handle loading javascript on your page, but this is the most foolproof one to use for modern browsers (for others, read script loading strategies). <script src="my-js-file.js" defer></script> note: the <sc...
Introduction to HTML - Learn web development
a navigation menu?), and embed content such as images and videos into a page. this module will introduce the first two of these and introduce fundamental concepts and syntax you need to know to understand html. looking to become a front-end web developer? we have put together a course that includes all the essential information you need to work towards your goal. get started prerequisites before starting this module, you don't need any previous html knowledge, but you should have at least basic familiarity with using computers and using the web passively (i.e., just looking at it and consuming content). you should have a basic work environment set up (as detailed in installing basic software), and understand how to create and manage files (as detailed in dealing with files). both are par...
From object to iframe — other embedding technologies - Learn web development
s for complex images and animations. peter elst was already writing some years ago that adobe flash is rarely the right tool for the job. as for activex, even microsoft's edge browser no longer supports it. test your skills! you've reached the end of this article, but can you remember the most important information? you can find some further tests to verify that you've retained this information before you move on — see test your skills: multimedia and embedding. summary the topic of embedding other content in web documents can quickly become very complex, so in this article, we've tried to introduce it in a simple, familiar way that will immediately seem relevant, while still hinting at some of the more advanced features of the involved technologies. to start with, you are unlikely to use ...
Multimedia and Embedding - Learn web development
teresting content! this module explores how to use html to include multimedia in your web pages, including the different ways that images can be included, and how to embed video, audio, and even entire webpages. looking to become a front-end web developer? we have put together a course that includes all the essential information you need to work towards your goal. get started prerequisites before starting this module, you should have a reasonable understanding of the basics of html, as previously 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 exa...
HTML table basics - Learn web development
Learn › HTML › Tables › Basics
"hippopotamus", and "crocodile" span across two columns. finally, use rowspan to make "horse" and "chicken" span across two rows. save and open your code in a browser to see the improvement. note: you can find our finished example at animals-table-fixed.html on github (see it live also). providing common styling to columns there is one last feature we'll tell you about in this article before we move on. html has a method of defining styling information for an entire column of data all in one place — the <col> and <colgroup> elements. these exist because it can be a bit annoying and inefficient having to specify styling on columns — you generally have to specify your styling information on every <td> or <th> in the column, or use a complex selector such as :nth-child(). note: st...
Assessment: Structuring planet data - Learn web development
objective: to test comprehension of html tables and associated features. starting point to start the assessment, make local copies of blank-template.html, minimal-table.css, and planets-data.txt in a new directory in your local computer. ...
HTML Tables - Learn web development
Learn › HTML › Tables
lesson plan, the timetable at your local swimming pool, or statistics about your favorite dinosaurs or football team. this module takes you through all you need to know about structuring tabular data using html. looking to become a front-end web developer? we have put together a course that includes all the essential information you need to work towards your goal. get started prerequisites before starting this module, you should already have covered the basics of html — see introduction to html. note: if you are working on a computer/tablet/other device where you don't have the ability to create your own files, you could try out (most of) the code examples in an online coding program such as jsbin or glitch. guides this module contains the following articles: html table basics ...
Introduction to events - Learn web development
d, you can set the click event listener on the parent <ul>, and events will bubble from the list items to the <ul>. this concept is explained further on david walsh's blog, with multiple examples — see how javascript event delegation works. test your skills! you've reached the end of this article, but can you remember the most important information? to verify you've retained this information before you move on — see test your skills: events. conclusion you should now know all you need to know about web events at this early stage. as mentioned, events are not really part of the core javascript — they are defined in browser web apis. also, it is important to understand that the different contexts in which javascript is used have different event models — from web apis to other areas s...
Image gallery - Learn web development
previous overview: building blocks now that we've looked at the fundamental building blocks of javascript, we'll test your knowledge of loops, functions, conditionals and events by getting you to build a fairly common item you'll see on a lot of websites — a javascript-powered image gallery. prerequisites: before attempting this assessment you should have already worked through all the articles in this module. objective: to test comprehension of javascript loops, functions, conditionals, and events. starting point to get this assessment started, you should go and grab the zip file for the example, unzip it somewhere on your computer, and do the exercise locally to begin with. alternatively, you could use a site like jsbin or glitch to do your assessmen...
Test your skills: Functions - Learn web development
te a function that draws a rectangle on the provided <canvas> (reference variable canvas, context available in ctx), based on the five provided input variables: x — the x coordinate of the rectangle. y — the y coordinate of the rectangle. width — the width of the rectangle. height — the height of the rectangle. color — the color of the rectangle. you'll want to clear the canvas before drawing, so that when the code is updated in the case of the live version, you don't get lots of rectangles drawn on top of one another. try updating the live code below to recreate the finished example: download the starting point for this task to work in your own editor or in an online editor. functions 3 in this task, you return to the problem posed in task 1, with the aim of improving...
Test your skills: Loops - Learn web development
ppended to the provided list. download the starting point for this task to work in your own editor or in an online editor. loops 2 in this next task, we want you to write a simple program that, given a name, searches an array of objects containing names and phone numbers (phonebook) and, if it finds the name, outputs the name and phone number into the paragraph (para) and then exits the loop before it has run its course. you are given three variables to begin with: i — starts off with a value of 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 wor...
JavaScript building blocks - Learn web development
commonly-encountered types of code blocks such as conditional statements, loops, functions, and events. you've seen this stuff already in the course, but only in passing — here we'll discuss it all explicitly. looking to become a front-end web developer? we have put together a course that includes all the essential information you need to work towards your goal. get started prerequisites before starting this module, you should have some familiarity with the basics of html and css, and you should have also worked through our previous module, javascript first steps. note: if you are working on a computer/tablet/other device where you don't have the ability to create your own files, you could try out (most of) the code examples in an online coding program such as jsbin or glitch. guide...
Storing the information you need — Variables - Learn web development
nday = 24; const works in exactly the same way as let, except that you can't give a const a new value. in the following example, the second line would throw an error: const daysinweek = 7; daysinweek = 8; test your skills! you've reached the end of this article, but can you remember the most important information? you can find some further tests to verify that you've retained this information before you move on — see test your skills: variables. summary by now you should know a reasonable amount about javascript variables and how to create them. in the next article, we'll focus on numbers in more detail, looking at how to do basic math in javascript. previous overview: first steps next in this module what is javascript? the first splash into javascript what went wrong? tro...
Solve common problems in your JavaScript code - Learn web development
while loops? how do you iterate over the elements in an array? how do you iterate over the elements in a multidimensional array? how do you iterate over the members in an object? how do you iterate over the members of an object nested inside a...
JavaScript object basics - Learn web development
passing — when an object needs another object to perform some kind of action often it sends a message to another object via one of its methods, and waits for a response, which we know as a return value. test your skills! you've reached the end of this article, but can you remember the most important information? you can find some further tests to verify that you've retained this information before you move on — see test your skills: object basics. summary congratulations, you've reached the end of our first js objects article — you should now have a good idea of how to work with objects in javascript — including creating your own simple objects. you should also appreciate that objects are very useful as structures for storing related data and functionality — if you tried to keep ...
Object-oriented JavaScript for beginners - Learn web development
it. one limitation of create() is that ie8 does not support it. so constructors may be more effective if you want to support older browsers. we'll explore the effects of create() in more detail later on. test your skills! you've reached the end of this article, but can you remember the most important information? you can find some further tests to verify that you've retained this information before you move on — see test your skills: object-oriented javascript. note that this set of tests relies on some of the knowledge taught in the next two articles, so you might want to read them first before you try the tests. summary this article has provided a simplified view of object-oriented theory — this isn't the whole story, but it gives you an idea of what we are dealing with here. in ad...
Test your skills: JSON - Learn web development
tore: the names of the three mother cats, separated by commas, in the motherinfo variable. the total number of kittens, and how many are male and female, in the kitteninfo variable. the values of these variables are then printed to the screen inside paragraphs. some hints/questions: the json data is provided as text inside the displaycatinfo() function. you'll need to parse it into json before you can get any data out of it. you'll probably want to use an outer loop to loop through the cats and add their names to the motherinfo variable string, and an inner loop to loop through all the kittens, add up the total of all/male/female kittens, and add those details to the kitteninfo variable string. the last mother cat name should have an "and" before it, and a full stop after it. how do ...
Test your skills: Object-oriented JavaScript - Learn web development
try updating the live code below to recreate the finished example: download the starting point for this task to work in your own editor or in an online editor. oojs 2 next up we want you to take the shape class you saw in task #1 (including the calcperimeter() method) and recreate it using es class syntax instead. test that it works by creating the square and triangle object instances as before (using new shape() for both), and then calling their calcperimeter() methods. try updating the live code below to recreate the finished example: download the starting point for this task to work in your own editor or in an online editor. oojs 3 finally, we'd like you to start with the es shape class you created in the last task. we'd like you to create a square class that inherits from s...
CSS performance optimization - Learn web development
g <video>, <canvas> and <iframe>, are also on their own layer. when an element is promoted as a layer, also known as composited, animating transform properties is done in the gpu, resulting in improved performance, especially on mobile. will-change property the css will-change property tells browsers which properties of an element are expected to change enabling browsers to set up optimizations before the element is actually changed, improving performance by doing potentially expensive work before it is required. will-change: opacity, transform; the font-display property applied to the @font-face rule, the font-display property defines how font files are loaded and displayed by the browser, allowing text to appear with a fallback font while a font loads, or fails to load. this improves perf...
Measuring performance - Learn web development
eport in seconds. the report contains scores about how your website is performing, both for mobile and desktop. this is a good start for getting an idea about what you are already doing well and what could be improved. at the time of writing, mdn's performance report summary looks similar to the following: a performance report contains information about things like how long a user has to wait before anything is displayed on the page, how many bytes need to be downloaded to display a page, and much more. it also lets you know it the measured values are considered good or bad. webpagetest.org is another example of a tool that automatically tests your site and returns useful metrics. try running your favorite website now, on both webpagetest.org and pagespeed insights, and see what the scores...
Web performance resources - Learn web development
nal 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 is by inlining css that is required for any content that is rendered above the fold, or what you see in the browser viewport before scrolling. these styles will improve perceived performance as the css does not require a file request. <style type="text/css"> // insert your css here </style> javascript avoid javascript blocking by using the async or defer attributes, or link javascript assets after the page's dom elements. javascript only block rendering for elements that appear after the script tag in the dom tree. web f...
The "why" of web performance - Learn web development
imagine loading this on a desktop computer connected to a fibre optic network. this would seem relatively fast, and the file size would be largely irrelevant. imagine loading that same site using tethered mobile data on a 9 year-old ipad while commuting home on public transportation. the same site will be slow to load, possibly verging on unusable depending on cell coverage. you might give up before it finishes loading. imagine loading that same site on a $35 huawei device in a rural india with limited coverage or no coverage. the site will be very slow to load—if it loads at all—with blocking scripts possibly timing out, and adverse cpu impact causing browser crashes if it does load. a 22.6 mb site could take up to 83 seconds to load on a 3g network, with domcontentloaded (meaning th...
Web performance - Learn web development
h as possible, however, it is good to focus specifically on such topics too, and make sure you are familiar with them. learning pathway while knowing html, css, and javascript is needed for implementing many web performance improvement recommendations, knowing how to build applications is not a necessary pre-condition for understanding and measuring web performance. we do however recommend that before you work through this module, you at least get a basic idea of web development by working through our getting started with the web module. it would also be helpful to go a bit deeper into these topics, with modules such 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 — yo...
Properly configuring server MIME types - Learn web development
just place the file in the parent directory; you need not place it in each subdirectory. if you're using a server-side script to generate content, you can generally add one line near the top of your script. you can serve content other than html from perl, php, asp, or java — just change the mime type accordingly. for perl cgi, you should have the line print "content-type: text/html\n\n"; before any other output lines. if you're using the cgi module, you can use the line print $cgi->header('text/html'); instead, where $cgi is your reference to the cgi instance. for php, you should have the line header('content-type: text/html'); before any other output lines. for asp, you should have the line response.contenttype = "text/html"; before any other output lines. for a java servlet, ...
Server-side website programming first steps - Learn web development
server-side programming — "what is it?", "how does it differ from client-side programming?", and "why is it so useful?". we then provide an overview of some of the most popular server-side web frameworks, along with guidance on how to select the most suitable framework for creating your first site. finally, we provide a high-level introductory article about web server security. prerequisites before starting this module, you don't need to have any knowledge of server-side website programming, or indeed any other type of programming. however, you do need to understand how the web works. we recommend that you first read the following topics: what is a web server? what software do i need to build a website? how do you upload files to a web server? with that basic understanding, you'll ...
Ember interactivity: Events, classes and state - Learn web development
lt class tododataservice extends service { @tracked todos = []; @action add(text) { let newtodo = new todo(text); this.todos = [...this.todos, newtodo]; } } here, the todos property on the service will maintain our list of todos contained inside an array, and we'll mark it with @tracked, because when the value of todos is updated we want the ui to update as well. and just like before, the add() function that will be called from the template gets annotated with the @action decorator to bind it to the class instance. this function's contents are fairly easy to understand — when the function is invoked, a new todo object instance is created with a text value of text, and the todos property value is updated to all of the current items inside the array (accessed conveniently usi...
Ember resources and troubleshooting - Learn web development
a route represents part of the url when a user navigates from place to place in the app. a route has only a couple responsibilities: load the minimally required data to render the route (or view-sub-tree). gate access to the route and redirect if needed. handle loading and error states from the minimally required data. a route only has 3 lifecycle hooks, all of which are optional: beforemodel — gate access to the route. model — where data is loaded. aftermodel — verify access. last, a route has the ability to handle common events resulting from configuring the model: loading — what to do when the model hook is loading. error — what to do when an error is thrown from model. both loading and error can render default templates as well as customized templates ...
Routing in Ember - Learn web development
ll want to pass an argument to the todolist component representing the "current list of todos", as shown here: {{#each @todos as |todo| }} and that's it for this tutorial! your app should now have fully working links in the footer that display the "index"/default, "active", and "completed" routes. summary congratulations! you've finished this tutorial! there is a lot more to be implemented before what we've covered here has parity with the original todomvc app, such as editing, deleting, and persisting todos across page reloads. to see our finished ember implementation, checkout the finished app folder in the repository for the code of this tutorial or see the live deployed version here. study the code to learn more about ember, and also check out the next article, which provides links t...
Componentizing our Svelte app - Learn web development
be called with an event object available, with the additional data available in the event.detail property. now we have to listen to that event from inside todos.svelte and act accordingly. go back to this file and update your <todo> component call like so: <todo {todo} on:remove={e => removetodo(e.detail)} /> our handler receives the e parameter (the event object), which as described before holds the todo being deleted in the detail property. at this point, if you try out your app again, you should see that the delete functionality now works again! so our custom event has worked as we hoped. in addition, the remove event listener is sending the daa change back up to the parent, so our "x out of y items completed" status heading will now update appropriately when todos are dele...
Deployment and next steps - Learn web development
h, and takes care of building and deploying your web site. to demonstrate this, we will deploy our todos app to gitlab pages. first you'll have to register at gitlab and then create a new project. give you new project a short, easy name like "mdn-svelte-todo". you will have a remote url that points to your new gitlab git repository, like git@gitlab.com:[your-user]/[your-project].git. before you start to upload content to your git repository, it is a good practice to add a .gitignore file to tell git which files to exclude from source control. in our case we will tell git to exclude files in the node_modules directory by creating a .gitignore file in the root folder of your local project, with the following content: node_modules/ now let's go back to gitlab. after creating a...
Getting started with Vue - Learn web development
e. select "in dedicated config files" and push enter. finally, you are asked if you want to save this as a preset for future options. this is entirely up to you. if you like these settings over the existing presets and want to use them again, type y , otherwise type n. the cli will now begin scaffolding out your project, and installing all of your dependencies. if you've never run the vue cli before, you'll get one more question — you'll be asked to choose a package manager. you can use the arrow keys to select which one you prefer. the vue cli will default to this package manager from now on. if you need to use a different package manager after this, you can pass in a flag --packagemanager=<package-manager>, when you run vue create. so if you wanted to create the moz-todo-vue project wit...
Rendering a list of Vue components - Learn web development
— where items is the array you want to iterate over, and item is a reference to the current element in the array. v-for attaches to the element you want to repeat, and renders that element and its children. in this case, we want to display an <li> element for every to-do item inside our todoitems array. then we want to pass the data from each to-do item to a todoitem component. key attribute before we do that, there's one other piece of syntax to know about that is used with v-for, the key attribute. to help vue optimize rendering the elements in the list, it tries to patch list elements so it's not recreating them every time the list changes. however, vue needs help. to make sure it is re-using list elements appropriately, it needs a unique "key" on the same element that you attach v-for t...
Cross browser testing - Learn web development
gate them, what tools are most useful in helping you test and fix problems, and how to use automation to speed up testing. 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 you should really learn the basics of the core html, css, and javascript languages first before attempting to use the tools detailed here. guides introduction to cross browser testing this article starts the module off by providing an overview of the topic of cross browser testing, answering questions such as "what is cross browser testing?", "what are the most common types of problems you'll encounter?", and "what are the main approaches for testing, identifying, and fixing problems?"...
Package management basics - Learn web development
save the file: "scripts": { "test": "echo \"error: no test specified\" && exit 1", "dev": "parcel serve index.html" }, we’ve added a custom dev command as an npm script. now try running the following in your terminal, making sure you are inside the parcel-experiment directory: npm run dev this should start parcel and serve up your index.html at the local development server, as we saw before: server running at http://localhost:1234 ✨ built in 5.48s. in addition, the npm (and yarn) commands are clever in that they will search for command line tools that are locally installed to the project before trying to find them through conventional methods (where your computer will normally store and allow software to be found). you can learn more about the technical intricacies of the run c...
Understanding client-side web development tools - Learn web development
nt-side tool types, explain the tools you can chain together, how to install them using package managers, and control them using the command line. we finish up by providing a complete toolchain example showing you how to get productive. get started now, with our "client-side tooling overview" prerequisites you should really learn the basics of the core html, css, and javascript languages first before attempting to use the tools detailed here. 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 guides 1. client-side tooling overview in this article we provide an overview of modern web tooling, what kinds of tools are available and where you’ll meet them in the lifecyc...
Chrome Worker Modules
orts = {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 initialization is complete. the module loader supports cyclic calls to require(). however, if you have cyclic requirements, some of the modules involved in the cyclic requirements may become visible by the other modules before they are fully evaluated. no attempt is made to fully isolate modules from each other. in particular, globals (string, math, object, self) and the worker global scope itself (this) are shared between workers. in other words, the true isolation unit is the worker itself, not the module. ...
Mozilla accessibility architecture
ach dom node in a hash table, we can hand back accessibles extremely quickly, and avoid recalculating and creating new accessibles every time one is requested for a certain dom node. we also avoid calculating the children of an accessible twice, once for getaccchildcount() and again when the specific children are requested. events: we must ensure that the accessible for an event is not released before the accessible client has 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 ...
Accessibility information for UI designers and developers
input, explain what is wrong and, if possible, how to correct it. this is specifically important in these cases: the user input is about legal commitments or financial transactions it updates or removes the user's data in a system when recording tests responses in those cases, ensure users can change submissions, automatically check for errors. or provide an opportunity to review the input before submitting it. use default controls controls that are built into browsers come with a lot of accessibility for free. for example, the select element displays an ideal mobile interface on mobile operating systems like android and ios. on desktop with a keyboard, it lets people type a character, say ‘k’, to jump directly to options starting with ‘k’. it is recommended to use native contro...
Embedding API for Accessibility
be extremely useful. for example, settings per url would allow a user to accept scripts from their known benign web pages, but not others. users may want similarity abilities with applets, background images, style sheets, etc. we have a permissions system for cookies and images based on url's. perhaps it can be extended to store accessibility preferences. this is a ui issue we'll need to settle before we know where to go with the embedding accessibility interface. ...
Mozilla’s UAAG evaluation report
(p2) vg html 4.01: vg css 1: vg css 2: vg dom 1.0: vg guideline 9. provide navigation mechanisms. checkpoint title status notes/plans 9.1 provide content focus. (p1) c provides a content focus 9.2 provide user interface focus. (p1) c provides a user interfa...
ZoomText
e considering they're only alpha, i'm having very good luck with them. it doesn't do us any good to get bug reports on older stuff right now. our main focus is on the browser itself, so you you only need to install mailnews or address book if curious about the other apps. you will also need to install zoomtext 8.11.3. happy testing! you may wish to read through the current issues on this page before reporting bugs. send me email so that i'm aware that you're testing and let me know what bugs you're finding. my email address is aaronleventhal@moonset.net. issues for ai squared, from high to low priority docreader and appreader don't respect the structure of the document -- no support for columns. zoomtext text to speech doesn't always echo what it should -- need more details from tester...
Index
rch engine results, through having an icon that attracts a user’s attention from a category list, to screenshots that show how useful your add-on is. 676 index add-ons, glossary, guide, index found 689 pages: 677 signing and distributing your add-on add-ons, extensions, webextensions, distribution, publication, reviews, signing add-ons need to be signed before they can be installed into release and beta versions of firefox. this signing process takes place through addons.mozilla.org (amo), whether you choose to distribute your add-on through amo or to do it yourself. 678 make money from browser extensions guide, monetization, webextensions, distribution while users can download browser extensions for firefox free of cost from addon...
Android-specific test suites
test this will run the tests and report the results to stdout, as well as produce an html report. while developing, you can launch these tests from within android studio, which is the fastest way to iterate on code and tests. disabling one failing test there is no manifest listing the android local unit tests. to disable a single test, edit the source code and insert junit's @ignore annotation before the existing @test annotation. for example, to disable org.mozilla.gecko.permissions.testsuccessrunnableisexecutedifpermissionsaregranted, add @ignore as follows: ... @runwith(testrunner.class) public class testpermissions { @ignore @test public void testsuccessrunnableisexecutedifpermissionsaregranted() { ... contact information android-test is currently owned by :sebastian and ...
Benchmarking
ox builds have a diagnostic tool that causes crashes to happen sooner and produce much more actionable information, but also slow down regular usage substantially. in particular, "gc poisoning" is used in all debug builds, and in optimized nightly builds (but not opt developer edition or beta builds). the poisoning can be disabled by setting the environment variable jsgc_disable_poisoning=1 before starting the browser. async stacks async stacks no longer impact performance since firefox 78, as bug 1601179 limits async stack capturing to when devtools is opened. another option that is on by default in non-release builds is the preference javascript.options.asyncstack, which provides better debugging information to developers. set it to false to match a release build. (this may be disab...
A bird's-eye view of the Mozilla framework
rendering of the document pages. the nglayout engine also parses xul ui controls into a dom tree and handles rendering of the ui. core services modules such as the nglayout engine comprise the core application services available to other core modules, and xul packages core application modules are implemented as a set of one or more xpcom (cross-platform com) objects. xpcom object model before getting into the details of the ui example, it's helpful to have a basic understanding of the xpcom object model. mozilla architectural modules are comprised of groups of related xpcom objects that provide services to and access services from each other through dynamically queryable interfaces. object model at a glance mozilla dynamically loads and integrates core modules and xul packages into ...
Browser chrome tests
e ignored by the test harness. using a descriptive file name is strongly encouraged instead of just using a bug number. you can collect common utils and helpers in a file called head.js, that must live in the same folder as the browser-chrome tests. this file will be injected into the test scope for each test living in the same folder. notice that any function call in head.js main scope will run before the main test() method. asynchronous tests when writing async tests, you can use the add_task method with promises. the test suite also supports asynchronous tests, using the same function names as mochitest. call waitforexplicitfinish() from test() if you want to delay reporting a result until after test() has returned. call finish() once the test is complete. be aware that the test harness w...
Cookies Preferences in Mozilla
kies from within mailnews or from mail-style uris false = allow cookies in these situations this preference is applicable to all versions of seamonkey. new in thunderbird 3 this preference is applicable to thunderbird 3 and later. earlier versions of thunderbird only allowed cookies on rss feeds. 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 be migrated when starting the application. (the old prefs are network.cookie.lifetime.enabled, network.cookie.lifetime.behavior, and network.cookie.warnaboutcookies.) true = prefs have been migrated false = migrate prefs on next startup original document information author(s): mike connor last updated date: may 22, 2004 copyright i...
Creating a Language Pack
_64 on linux or mac/xpi on mac. open the xpi file contained in this directory with firefox to see your work. you have to set your selected language still. you can either use the locale switcher extension, or set it in about:config. add the preference intl.locale.requested and set it to your language code, in this case, x-testing, or add it in front of the current setting, seperated with a comma. before gecko 59 you had to set the preference general.useragent.locale to your language code. l10n binary repack for apps currently in development, you need to get the right strings for the build you use. best is to create an installer there. first, we get the en-us builds. there is a target to get those, too, another way to test it to repack the en-us binary. from the obj-firefox-build/browser/loca...
Debugging OpenGL
— click an appropriate platform's debug build on the left, e.g. linux64-debug, then find the build link on the right hand side (this would be target.tar.bz2 for linux, target.dmg for macos, and target.zip for windows). if you need more verbose debug output, you can enable the verbose debug mode by defining the environment variable moz_gl_debug_verbose. with this enabled, messages are printed before and after every opengl call. this can help make it much easier to debug crashes and hangs that make the computer unusable (thereby stymieing attempts to debug). the moz_gl_debug_abort_on_error environment variable, if set, causes firefox to abort as soon as an opengl error occurs. this is generally only useful in cases where you know that no error should occur, since there are cases where perfec...
Articles for new developers
when first getting started as a contributor to the mozilla project, there's a lot of information to sort through and understand. to help you find the most critical stuff as quickly as possible, we've created this list of the articles you'll find most useful as you get yourself oriented and make your first contributions to the project. also, before you go any further, we'd like to welcome you to the mozilla community of developers! we look forward to your input! contributing to the mozilla code base this page should guide you through the initial steps of contributing to mozilla. welcome, we're delighted to see you! :) ...
Makefile - variables
exports_${namespace} a list of exports/headers that should be copied into the exported namespace directory. extra_components nsdefaultclh.manifest, javascript xpcomm files extra_dso_libs extra_dso_ldopts extra_js_modules extra_pp_components xpcomm files to pre-process before installation. garbage a "clean target" macro containing a list of files 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 mic...
How Mozilla's build system works
into it, and validate everything looks ok to build. the primary output of the configure script is an executable file in the object directory called config.status. configure also produces some additional files (like autoconf.mk). however, the most important file in terms of architecture is config.status. the existence of a config.status file may be familiar to those who have worked with autoconf before. however, mozilla's config.status is different from many other config.status files, as it's written in python! instead of our configure script producing a shell script, it generates a python script. python 2 is prevalent in a mozilla build system. if we need to write code for the build system, we do it in python 2 instead of editing a makefile. config.status contains 2 parts: data structures...
Updating NSPR or NSS in mozilla-central
y mistake, your change will be lost when the nspr and nss teams push a new hg tag to mozilla-central. ...
Commenting IDL for better documentation
ists should be indented from the previous level by two spaces. other tips some other helpful writing style tips that will help you make your comments cleaner and easier to read and understand: you don't need to include what a method returns in the description. just include the @returns line. this helps avoid repetition and keeps your comment more streamlined. everything in the doxygen comment before a method, attribute, constant, or whatnot will be used as part of its description when the automatic documentation generator tool scans your idl, so if you don't want it in the docs, you probably shouldn't put it there. use a different format of comment instead, such as simply /* ... */ or even // comment. example this is an example of what the sample interface document idl would look like: /** ...
Contributing to the Mozilla code base
ugh the initial steps of contributing to mozilla. welcome, we're delighted to see you! :) need help? the mozilla community prides itself on being an open, accessible, and friendly community for new participants. if you have any difficulties getting involved or finding answers to your questions, 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. if you're having any trouble following this documentation, or hit a barrier you can't get around, please contact mike hoye at mhoye@mozilla.
Listening to events on all tabs
nsidomxulelement abrowser, nsiwebprogress webprogress, nsiuri arefreshuri, long amillis, boolean asameuri ); parameters abrowser the browser that fired the notification. awebprogress the nsiwebprogress instance that fired the notification. arefreshuri the new uri that awebprogress has requested redirecting to. amillis the delay (in milliseconds) before refresh. asameuri true if awebprogress is requesting a refresh of the current uri. false if awebprogress is requesting a redirection to a different uri. return value true if the refresh may proceed. false if the refresh should be aborted. onlinkiconavailable notification that the site icon for a browser has been found. void onlinkiconavailable( nsidomxulelement abrowser, ); param...
SVG Guidelines
svg provides a lot of flexibility in terms of scaling, themability, etc. this flexibility depends on doing computations for svg images at the time they're displayed, rather than at the time the author creates them. consider an image that involves some complex gradients and filters. if saved as a raster image then the work to rasterize the gradients and filters takes place on the authors computer before the result is stored in the raster file. this work doesn't need to be redone when the image is displayed on someone else's computer. on the other hand, if the image is saved as an svg image then all this work needs to be done each time the svg is displayed on someone else's computer. this isn't to say that svg images are always slower than raster equivalents. in fact it can be faster to send vect...
mach
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. for zsh, you can call the built-in bashcompinit function before sourcing: autoload bashcompinit bashcompinit source /path/to/mozilla-central/python/mach/bash-completion.sh frequently asked questions why should i not use mach? a real faq for a change! mach is not the best software ever. say, if you run a rolling release arch linux distro or derivate thereof ("manjaro"), you have something less tedious: octopi! just install thunderbird from sources out of...
Developer guide
es. in active development. mozilla build vm a virtualbox compatible virtual machine configured with all the software needed to build and work on firefox. taskcluster taskcluster is the task execution framework that supports mozilla's continuous integration and release processes. treeherder treeherder shows the status of the tree (whether or not it currently builds successfully). check this before checking in and out, to be sure you're working with a working tree. perfherder perfherder is used to aggregate the results of automated performance tests against the tree. crash tracking information about the socorro crash reporting system. callgraph a tool to help perform static analysis of the mozilla code by generating callgraphs automatically. developer forums a topic-specific list of...
Cross Process Object Wrappers
"\n"); }); this sends a message asking the frame script to change the current document uri, then accesses the current document uri via a cpow. you might expect the value of uri to come back as "hello.com". but it might not: in order to avoid deadlocks, cpow messages can bypass normal messages and be processed first. it’s possible that the request for the documenturi property will be processed before the "changedocumenturi" message, in which case uri will have its previous value. for this reason, it’s best not to mix cpows with normal message manager messages. it’s also a bad idea to use cpows for anything security-related, since you may get results that are not consistent with surrounding code that might use the message manager. safe and unsafe cpows the main reason cpows can be bad...
Frame script environment
er to avoid handling unload events from content. does not bubble. domwindowcreated fires when a new content object is created. this can be used if a framescript needs to interact with individual dom windows instead of simply listening for events bubbling up from content. another use is to interact with the content very early in the page load process, long before domcontentloaded event is fired. ...
Limitations of chrome scripts
== "http-on-modify-request") { var httpchannel = subject.queryinterface(ci.nsihttpchannel); var loadcontext = httpchannel.notificationcallbacks.getinterface(ci.nsiloadcontext); // topframeelement is the <browser> element var topframeelement = loadcontext.topframeelement; var browsermm = topframeelement.messagemanager; console.log("browsermm: " + browsermm); } } however, before firefox 38, this technique will not work if multiprocess firefox is disabled: specifically, topframeelement will be null. this means that if you need to write code that works before firefox 38 and on both multiprocess and non-multiprocess variants, you need to implement both paths: test whether topframeelement is null if it is, you're running in single-process firefox, and should use the old ...
Frame script environment
agemanager global object to avoid handling unload events from content. domwindowcreated fires when a new content object is created. this can be used if a framescript needs to interact with individual dom windows instead of simply listening for events bubbling up from content. another use is to interact with the content very early in the page load process, long before domcontentloaded event is fired. ...
Frame script loading and lifetime
oadcasts "disable" to your frame scripts. your add-on is upgraded, and the new code loads new frame scripts. the new frame scripts receive the "disable" message and stop working. in fact, the message manager guarantees that loadframescript and broadcastasyncmessage are guaranteed to affect frame scripts in the order that they are called, so in this case "disable" will be received and consumed before the new frame scripts are loaded. at the moment, frame scripts are cached until the browser restarts: this problem is tracked as bug 1051238. this is a problem especially for restartless add-ons; because when a new version of the add-on is installed, the old frame scripts will not be unloaded. the workaround is to randomize the frame script's url; for example, by appending "?" + math.random(). ...
Security best practices for Firefox front-end engineers
tizerallowcomments 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 early on in the development cycle and before shipping the code. linter rules against unsanitized dom interaction the security assurance team maintains an eslint rule that disallows unsafe uses of innerhtml and similar dom apis. the linter makes an exception for code that uses string literals that are hard coded in the source code, assuming benevolent developers. developers are able to avoid tripping the rule by using escaping functions ...
Using the Browser API
Mozilla › Gecko › Chrome › API › Browser API › Using
it on production sites facing the web: it will not work for every user. there may also be large incompatibilities between implementations and the behavior may change in the future. the html browser api is an extension of the html <iframe> element that allows web apps to implement browsers or browser-like applications. it was originally used in firefox os to implement browser applications before that project was cancelled; since firefox 47 it is available to desktop chrome code and used in places like the firefox devtools. it consists of two major parts: custom <iframe> attributes: by adding a mozbrowser attribute to the <iframe> element we can make it appear like a top-level browser window to the embedded content. this means that window.top, window.parent, window.frameelement, etc. ...
HTMLIFrameElement.getScreenshot()
warning: removed in firefox 65. the getscreenshot() method of the htmliframeelement lets you request a screenshot of a content <iframe>, scaled to fit within a specified maximum width and height. the image will be cropped if necessary but will not be distorted vertically or horizontally. note: getscreenshot() waits for the event loop to go idle before it takes the screenshot. it won't wait more than 2000ms (this delay is defined by the gecko dom.browserelement.maxscreenshotdelayms preference). syntax var instanceofdomrequest = instanceofhtmliframeelement.getscreenshot(maxwidth, maxheight, mimetype); returns a domrequest for handling the screenshot request. its request.onsuccess handler handles the success case (the screenshot is contained in request.result as a blob object)...
Chrome-only Events reference
this page lists events that are only available in gecko chrome code (and sometimes in other privileged circumstances, eg. ua widgets). mozbeforepaintgecko 2.0 adds a new method for performing javascript controlled animations that synchronize not only with one another, but also with css transitions and smil animations being performed within the same window.mozscrolledareachangedthe mozscrolledareachanged event is fired when the document view has been scrolled or resized. smartcard-insertthe smartcard-insert event is fired when the insertion of a smart card has been detectedsmartcard-removethe smartcard-remove event is fired when the removal of a smart card has been detected. ...
Overview of Mozilla embedding APIs
// always nsnull. x, y, cx, cy); // initial dimensions... if (ns_failed(rv)) return rv; // create the child window for the webbrowser. rv = basewindow->create(); if (ns_failed(rv)) return rv; // at this point webbrowser contains the new initialized instance // of the nswebbrowser component... // save webbrowser before it goes out of scope :-) web navigation the nsiwebnavigation interface is used to load uris into the webbrowser and provide access to session history capabilities - such as back and forward. clipboard the webbrowser exposes access to the system clipboard via the nsiclipboardcommands interface. this interface supports cut/copy/paste operations on the current selection within the webbrowser windo...
Gecko SDK
r and the latest npapi.h. get the sdk updates there is no need to download or rebuild the gecko sdk corresponding to security updates of mozilla (e.g., mozilla 1.7.3) since the headers and glue libs in the gecko sdk are usually not changed as a result of security updates. you do have to get and distribute the newest gecko components (gklayout.dll etc.), though. downloading for gecko versions before 2.0, you should choose the gecko sdk version for the earliest version of mozilla you wish to target. for gecko versions 2.0 and higher, you must recompile your component for each release as cross-version compatibility is no longer supported. in addition to the below versions, you can find other versions (including beta) here: xulrunner releases (files include "sdk" in the name). the sdk follow...
Hacking with Bonsai
e build team will then pull the 8:00 am tree, and build it on a subset of the platforms, linux, win32 & macppc. at 10:00 am, everyone who is on the hook is available in case the build breaks eventually, the tree builds, and it is re-opened. there is a web page, which records if the tree is open or closed what the date stamp of the last known good tree is who is on the hook for the current tree before the tree is opened, the list of checkins that happened when the tree was closed is reviewed to insure that only build related checkins took place. before the tree is opened, there is a car pool lane where people who have been off on a branch and need a stable tip to merge in can pull the tip for their merge. these people, when they check in, will be "on the hook" for the next day's build. the car...
IPDL Tutorial
} private: prlibrary* mpluginlibrary; }; launching the subprocess and hooking these protocol actors into our ipc "transport layer" is beyond the scope of this document. see ipdl processes and threads for more details. because protocol messages are represented as c++ methods, it's easy to forget that they are in fact asynchronous messages: by default the c++ method will return immediately, before the message has been delivered. the parameters of the recv* methods (const nscstring& pluginpath in the example) are references to temporary objects, so copy them if you need to keep their data around. direction each message type includes a "direction." the message direction specifies whether the message can be sent from-parent-to-child, from-child-to-parent, or both ways. three keywords serv...
Implementing Download Resuming
the channel as usual (using nsichannel.asyncopen() in the common case) and write to the file in the ondataavailable notifications. you may want to use nsisimplestreamlistener to simplify this task; to get progress notifications, you can implement nsiprogresseventsink and set an interface requester as the notificationcallbacks of the channel that gives out such an event sink (this needs to be done before calling asyncopen). note: in versions of firefox prior to 3.0 alpha 7, nsiwebbrowserpersist cannot append to existing files (as opposed to overwriting them), and is therefore not usable for this task (see bug 129921). detecting when a file changed if the file changed (that is, the entity id does not match), then necko will notify the stream listener with an ns_error_entity_changed error code. ...
Infallible memory allocation
ranteed 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 remain so. when using these, you must check to ensure the resulting value isn't null before attempting to use the returned memory. p = malloc(); p = realloc(); namespace mozilla { f = new (fallible) foo(); farray = new (fallible) foo[]; } namespace mozilla { n = ::operator new(..., fallible); narray = ::operator new[](..., fallible); } see also choosing the right memory allocator ns_alloc() ...
Addon
getaddon methods on the addonmanager object. the interface can represent many different kinds of add-ons and as such, some of the methods and properties are considered "required" and others "optional," which means that the optional methods or property may not exist on addon instances for some types of add-ons. api consumers should take care to verify the existence of these methods or properties before relying on them. overview of required methods void iscompatiblewith(in string appversion, in string platformversion) void findupdates(in updatelistener listener, in integer reason, in string appversion, in string platformversion) overview of optional methods void uninstall() void canceluninstall() boolean hasresource(in string path) ...
AddonManager
one of the forces of the addonmanager is that it deals with any kind (type) of add-on in a generic manner. ...
Code Samples
var beinguninstalled; let listener = { onuninstalling: function(addon) { if (addon.id == "youraddon@youraddon.com") { beinguninstalled = true; } }, onoperationcancelled: function(addon) { if (addon.id == "youraddon@youraddon.com") { beinguninstalled = (addon.pendingoperations & addonmanager.pending_uninstal...
Add-on Manager
api. all of its functions are asynchronous, meaning that a callback function must be passed to receive the addon instances. the callback may well only be called after the api function returns. for example: components.utils.import("resource://gre/modules/addonmanager.jsm"); addonmanager.getalladdons(function(aaddons) { // here aaddons is an array of addon objects }); // this code will execute before the code inside the callback notifications about changes to installed add-ons are dispatched to any registered addonlisteners. they must be registered through the addaddonlistener() method. installing new add-ons new add-ons can be installed by using the getinstallforfile() or getinstallforurl() methods on the addonmanager object. these will pass an addoninstall instance to the callback, whic...
API-provided widgets
vent handler name description onbuild(adoc) only useful for custom widgets (and required there); a function that will be invoked with the document in which to build a widget. should return the dom node that has been constructed. nb: the dom node you construct should have the same id as the id property described above, so that customizableui can find the node again later. onbeforecreated(adoc) attached to all non-custom widgets; a function that will be invoked before the widget gets a dom node constructed, passing the document in which that will happen. this is useful especially for 'view' type widgets that need to construct their views on the fly (e.g. from bootstrapped add-ons). oncreated(anode) attached to all widgets; a function that will be invoked ...
Dict.jsm
onary by simply calling the dict() constructor: var newdict = new dict(); if you wish, you may also pass in an object literal of key/value pairs with which to initialize the dictionary: var someobj = {}; var newdict = new dict({key1: "foo", key2: someobj}); note that values may be any javascript object type. note: you can actually specify non-strings as keys; these are converted to strings before being used, so they're documented here as if they were a string parameter. in firefox 19 and above, you may also pass a json string to initialize the dictionary: var somejson = '{key1: "foo", key2: {}}'; var newdict = new dict(somejson); note: any string you pass will be assumed to be json. method overview dict copy(); boolean del(string akey); object get(string a...
Downloads.jsm
work on downloads that were started from a private browsing window. all work on both downloads.private and downloads.public downloads. properties attribute type description error read only constructor constructor for a downloaderror object. when you catch an exception during a download, you can use this to verify if ex instanceof downloads.error, before reading the exception properties with the error details. example (using task.jsm): try { yield downloads.fetch(sourceuri, targetfile); } catch (ex if ex instanceof downloads.error && ex.becausetargetfailed) { console.log("unable to write to the target file, ignoring the error."); } methods createdownload() creates a new download object. promise<download> createdownload( o...
Interfacing with the Add-on Repository
the add-on repository javascript code module makes it easy for your extension to interface with the amo repository. you an use the code module to get lists of add-ons and even install new add-ons. this article provides some sample code that queries the recommended add-ons list on amo and lets the user click a button to install an add-on from the list. importing the repository code module before you can use the add-on repository api, you need to import the code module: components.utils.import("resource://gre/modules/addonrepository.jsm"); having done this, you can then access the api through the resulting addonrepository object. enabling the recommendation feature in current builds of firefox 4, the recommendation api doesn't work because the preference for the url to query to get recomme...
JNI.jsm
the jni.jsm javascript code module abstracts all of the js-ctypes required for writing jni code. to use it, you first need to import the code module into your javascript scope: components.utils.import("resource://gre/modules/jni.jsm"); this module was available in firefox since version 17. if you would like to support versions before that, you can copy and paste the contents of the jsm file int jni stands for java native interface; this library allows calling java code running in java virtual machines (jvms), etc. the most common use for this module is in add-ons and other works on firefox for android (fennec). with this module, all of the android sdk functions that firefox has permissions for are at your fingertips. a note about firefox for android, this jsm file is already globally impor...
JavaScript OS.Constants
s library directory. maclocalapplicationsdir the path to the local applications directory. os.constants.libc constants for interacting with libc. useful mostly for using js-ctypes to interact with the following platforms: macos x; android; linux; other variants of unix. os.constants.libc is available on all platforms, although some constants are not defined everywhere. before using a constant, you should check that it is defined. error values eacces permission denied eagain resource temporarily unavailable ebadf bad file descriptor eexist file exists efault bad address efbig file too large einval invalid argument eio input/output error eisdir is a directory ...
OS.File.Info
ibutes isdir true if the file is a directory, false otherwise. issymlink true if the false is a symbolic link, false otherwise. (as of firefox 38 this is always true on all systems, this is a bug: bugzilla 1145885) (on windows this returns false for hard links) size the number of bytes in the file. creationdate deprecated in bugzilla :: bug 807875. before deprecation, this used to be the date at which the file was created on windows and mac os x, as a javascript date object. on unix systems it was returning the last modified date and thus it was deprecated. there is talk of reinstating this with proper functionality in bugzilla :: bug 1167143. the creationdate can be obtained on windows by winbirthdate and on mac os x by macbirthdate. on older uni...
PerfMeasurement.jsm
the perfmeasurement.jsm javascript code module lets you take detailed performance measurements of your code. note: the perfmeasurement.jsm javascript code module can only be used from chrome -- that is, from within the application itself or an add-on. before you can use this module, you need to import it into your scope: components.utils.import("resource://gre/modules/perfmeasurement.jsm") see measuring performance using the perfmeasurement.jsm code module for details on how to use this api. note: at present, perfmeasurement.jsm is only functional on linux, but it is planned to add support for windows (bug 583322) and osx (bug 583323) as well, and we welcome patches for other operating systems. method overview static bool canmeasuresomething(); void reset(); void start(); void stop()...
Deferred
n existing promise. if the associated 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. note: calling this method with a pending promise as the avalue argument, and then calling it again with another value before the promise is resolved or rejected, will have 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 wi...
Examples
this copy/paste code here will complete succesfully: components.utils.import("resource://gre/modules/promise.jsm"); var mypromise = myuserdefinedpromise(); mypromise.then( function(asuccessreason) { alert('mypromise was succesfu...
Promise.jsm
its usage is not suggested for new code. if you just need a promise, consider using a dom promise instead. if you need a deferred, because you want to create a promise and manually resolve or reject it, consider using promiseutils.jsm instead. ...
Deferred
ate of an existing promise. if the associated promise has already been resolved, either to a value, a rejection, or another promise, this method does nothing. note: this function is exactly same as promise constructor's resolve argument, and can be called with any value of this. note: calling this method with a pending promise as the avalue argument, and then calling it again with another value before the promise is resolved or rejected, will have 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 wi...
SourceMap.jsm
ototype.tostring() renders the source map being generated to a string. sourcenode sourcenodes provide a way to abstract over interpolating and/or concatenating snippets of generated javascript source code, while maintaining the line and column information associated between those snippets and the original source code. this is useful as the final intermediate representation a compiler might use before outputting the generated js and source map. new sourcenode(line, column, source[, chunk]) line: the original line number associated with this source node, or null if it isn't associated with an original line. column: the original column number associated with this source node, or null if it isn't associated with an original column. source: the original source's filename. ...
Application Translation with Mercurial
ting the functionality it describes). this guide achieves this with the firefox extension scrapbook. you installed scrapbook earlier, now open it in firefox either by calling it from the firefox menu bar (press the alt key to show it if necessary) using "view" > "sidebar" > "scrapbook" or by clicking its toolbar button which you likely have to add by toolbar customization if you didn't do this before. drag the tab with the localization error showing missing and obsolete strings to the sidebar. after scrapbook has saved the web page to your local disk, click with the right mouse button on the page in the sidebar and choose "properties" from the context menu which gets opened. rename it something meaningful, e.g. "firefox <version number> translation". after you saved the dialog, click with ...
Index
initial setup localization as a pre-requisite to contributing to the l10n program, you need to have access to code, tools, and a properly configured local environment (i.e., your personal computer). you also need to determine if a localization effort already exists for your locale. here we'll go over the accounts you need as well as the tools and their configurations you need to set up before contributing. 14 qa phase localization after all of your hard work localizing we're sure that you not only want to see your work but you want to make sure it's accurate! if you don't have a lot of experience with code, you might even be concerned that you've broken something (oops!). now we'll walk you through performing some quality assurance testing on your work to make sur...
Localization and Plurals
le as well as getting methods to localize to a desired plural rule. the latter ability of specifying a plural rule is useful for extensions because the extension doesn't necessarily have to be localized to the browser's locale. loading pluralform.jsm loading the pluralform module from javascript is simple with components.utils.import. just put the following line somewhere that will be evaluated before you want to use pluralform. at the top of your javascript file is fine. components.utils.import("resource://gre/modules/pluralform.jsm"); methods: get these methods make use of the browser's current locale specified by chrome://global/locale/intl.properties's pluralrule value. /** * get the correct plural form of a word based on the number * * @param anum * the number to decide whi...
Localizing extension descriptions
most general one (e.g., en in preference to en-gb when searching for en-us). the current app locale will be searched for and then there will be a fallback search for en-us. if a preference isn't set and there isn't a matching em:localized property for the current locale or en-us, then the properties specified directly on the install manifest are used as a last resort, as they were always used before gecko 1.9. localizing before gecko 1.9 before gecko 1.9, add-on developers must go through a special process to define localized add-on descriptions for add-ons targeting toolkit-based apps (such as firefox or thunderbird). if you do not currently have them, create localized properties files. make sure to use utf-8 encoding (without bom) to ensure foreign characters display correctly. add ...
Localizing with Mozilla Translator
om dir instead of jar'' and ''put everything inside platform neutral''. that has worked well (ok, more or less) :-) as long as you could instruct mt to use just one ''root'' l10n directory, but this is no longer the case with mercurial. mt could be changed for a mt product to have a list of ''root'' directories instead of just one, and maybe someday it will do, but it will probably won't happen before seamonkey 1.1.x dies (and seamonkey 2.0 finally conquers the web, if i may add). ;-) enough chatting, what's next? anyway, we need to work around the full-fledged repository problem. these are your options: create one product for each ''root'' directories. this means browser, extensions/reporter, dom, netwer, security, and toolkit. besides that, you will need to create one tiny product fo...
Initial setup
as a pre-requisite to contributing to the l10n program, you need to have access to code, tools, and a properly configured local environment (i.e., your personal computer). you also need to determine if a localization effort already exists for your locale. here we'll go over the accounts you need as well as the tools and their configurations you need to set up before contributing. new or existing before anything else, you need to know if you will be creating a new localization or joining an existing one. this will determine what information is most applicable to you throughout the rest of this guide. here's what you do: look through the existing localization community directory to see if one already exists for your locale. if a community already exists, reach out to them and ask ho...
Translation phase
hacks.mozilla.org for everyone interested in the leading-edge stuff that people are doing with mozilla firefox and the open web. in-product pages a set of pages used to interact with and give information to the end-user as part of their first experience with their mozilla applications. if you are creating your own localization, there are a number of mozilla websites that need to be localized before your efforts become an officially released localization. see the list of localized mozilla websites. you should also read more information on localizing mozilla web projects. add-ons l10n for add-ons is handled by at least two other organizations/services called babelzilla and adofex. they both have created comprehensive programs and l10n tools for localizing any and all third-party add...
Localization quick start guide
ou should be able to make a change to firefox in your local setting and then see that change in the firefox interface. in closing, when you finish this guide, you will have all the tools necessary to start contributing! remember, this guide will instruct you on the technical aspects of mozilla l10n only. visit the l10n process page to learn about the whole process. initial setup tech prep work before localizing. translation phase l10n tools tutorials for translation. qa phase l10n testing tutorials. release phase steps to shipping your localization work. these four stages make up tech side of the l10n program. to learn more about any of these, click on any of the links above. to get the big picture, we suggest you start with the green bubble and move from stage to stage. note: this ...
Uplifting a localization from Central to Aurora
018_relbranch here you can see that there are two changesets without a branch. so yes, you need to merge those two. hg merge if this just passes, you want to commit, and you probably want to use a commit message like "merging central and aurora". you can safely push this to l10n-central already, in particular if you don't plan to do further updates on aurora. you don't want to push this to aurora before there's been the notification that the status of aurora has been lifted up to beta. if hg merge starts asking you questions, you have a merge conflict. that indicates that the same string has different translations on l10n-central and aurora, and you really want to make sure that your aurora clone doesn't have quality issues. in particular, did you land all the fixes for your work on both central...
Localization formats
html/php maybe you are designing a project that has relatively small translation needs like three to four lines (or more) of content asking users to update to the next version of software available. you may choose to present just the html for localization: we give an html file which lists several pieces of content like, <h1>getting started</h1> and the local...
What every Mozilla translator should know
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 process. if you choose to make any changes to the productization elements (i.e. search plugins, protocol handlers, rss/live bookmarks), you will need to upload a patch with the suggested changes to bugzilla and get approval before pushing those changes to your hg repository. do the changes in your local disk create a diff file with the changes $ hg diff -p -u 8 filename create a new bug: product: mozilla localization component: your language ... cc: l10n@mozilla.com assigned to: you explain what you need! specify the branch (1.9.2 for firefox 3.6, 1.9.2.1 for firefox 3.6.1, ...) attach the diff file to the...
MathML In Action
hml project page, and if you are building your own mozilla binary, see the directory mozilla/layout/mathml/tests. now, what next? as you try out mathml in mozilla, what to do with those few things that appear to you not to work as per the mathml spec? or what about those things that just seem itchy, and that you wish could be done just a little better? or what about those things that were working before and are not working anymore (a.k.a. regressions)? in either case, head over to bugzilla to report the discrepancies. bugzilla has a big memory for these things, and besides, how would your problems be fixed if they are not reported?! getting involved is part of your contribution towards enriching gecko with an elegant standards-compliant mathml renderer. your feedback can be manifested by putting...
Mozilla Style System Documentation
ing a style context: nsiprescontext::resolvestylecontextfor, nsiprescontext::resolvepseudostylecontextfor, and.nsiprescontext::resolvestylecontextfornonelement there is also a fourth method, nsiprescontext::probepseudostylecontextfor, which creates a style context only if there are style rules that match the pseudo-element. this is useful for the pseudo-elements defined in the css specification (:before, :after, :first-line, :first-letter), but few of mozilla's custom pseudo-elements, many of which are hacks for further formatting objects that we create. the pres context forwards these calls to its style set object (stylesetimpl, interface nsistyleset), which does the real work (and also maintains the lists of stylesheets and owns the rule tree). these methods may all return an existing style co...
Are We Slim Yet
es by default, we moved awsy into the taskcluster infrastructure. this allowed us to run measurements on all branches and platforms. the results are posted to perfherder where we can track regressions automatically. as new processes are added to firefox we want to make sure their memory usage is also tracked by awsy. to this end we request that memory reporting be integrated into any new process before it is enabled on nightly. ...
BloatView
cts allocated of a given class by the class size. note that although this isn't necessarily the amount of memory consumed at any given time, it does give an indication of how much memory we're consuming. the more memory in general, the worse the performance and footprint. the percentage 99999.99% will show up indicating an "infinite" amount of leakage. this happens when something that didn't leak before is now leaking. bloatview and continuous integration bloatview runs on debug builds for many of the test suites mozilla has running under continuous integration. if a new leak occurs, it will trigger a test job failure. bloatview's output file can also show you where the leaked objects are allocated. to do so, the xpcom_mem_log_classes environment variable should be set to the name of the cla...
Investigating leaks using DMD heap scan mode
s of cycle collected (cced) objects. dmd heap scan mode is a "tool of last resort" that should only be used when all other avenues have been tried and failed, except possibly ref count logging. it is particularly useful if you have no idea what is causing the leak. if you have a patch that introduces a leak, you are probably better off auditing all of the strong references that your patch creates before trying this. the particular steps given below are intended for the case where the leaked object is alive all the way through shutdown. you could modify these steps for leaks that go away in shutdown by collecting a cc and dmd log prior to shutdown. however, in that case it may be easier to use refcount logging, or rr with a conditional breakpoint set on calls to release() for the leaking object,...
Leak-hunting strategies and tips
's much better to go after the large graphs of leaks first. a good general pattern for finding and fixing leaks is to start with a task that you want not to leak (for example, reading email). start finding and fixing leaks by running part of the task under nstracerefcnt logging, gradually building up from as little as possible to the complete task, and fixing most of the leaks in the first steps before adding additional steps. (by most of the leaks, i mean the leaks of large numbers of different types of objects or leaks of objects that are known to entrain many non-logged objects such as js objects. seeing a leaked globalwindowimpl, nsxulpdglobalobject, nsxbldocglobalobject, or nsxpcwrappedjs is a sign that there could be significant numbers of js objects leaked.) for example, start with brin...
Leak Gauge
ocess the log file. getting a log file to get a log file, run the browser with the following environment variables set. nspr_log_modules=domleak:5,documentleak:5,nsdocshellleak:5,nodeinfomanagerleak:5 nspr_log_file=nspr.log # or any other filename of your choice this will overwrite any existing file called nspr.log. the browser will run with negligible slowdown. you must exit the browser before post-processing the log file or the results will be unreliable. post-processing a log file post-process the log file with tools/leak-gauge/leak-gauge.pl or tools/leak-gauge/leak-gauge.html. if there are no leaks, output will look like the following. results of processing log leak.log : summary: leaked 0 out of 11 dom windows leaked 0 out of 44 documents leaked 0 out of 3 docshells leaked cont...
Measuring performance using the PerfMeasurement.jsm code module
(let i = 0; i < 10000; i++) { set_up_some_state(); monitor.start(); code_to_be_benchmarked(); monitor.stop(); clean_up_afterward(); } we call the perfmeasurement object's start() method when we want to start recording, and stop() when we want to stop recording. this lets us record information only for the specific code section we want to measure. since we enable monitoring immediately before calling code_to_be_benchmarked(), and disable it as soon as it returns, the code in set_up_some_state() and clean_up_afterward() is not measured. the monitor object automatically accumulates counts over start/stop cycles (that is, it doesn't automatically zero the counters each time you start recording). when you're done benchmarking, you can read out each of the counters you asked for as prop...
Memory reporting
and please ask nnethercote to co-review any memory reporter patch. mozilla code has infrastructure that lets different parts of the code report on their memory usage. this is most obviously used in about:memory and telemetry. this document describes things that you should know when writing a memory reporter. memory reporters a memory reporter makes one or more memory measurements (a.k.a. reports). ...
Refcount tracing and balancing
3ab0 < my-leak.log this will build an indented tree that looks something like this (except probably a lot larger and leafier): .root: bal=1 main: bal=1 dosomethingwithfooandreturnittoo: bal=2 ns_newfoo: bal=1 let's pretend in our toy example that ns_newfoo() is a factory method that makes a new foo and returns it. dosomethingwithfooandreturnittoo() is a method that munges the foo before returning it to main(), the main program. what this little tree is telling you is that you leak one refcount overall on object 0x00253ab0. but, more specifically, it shows you that: ns_newfoo() "leaks" a refcount. this is probably "okay" because it's a factory method that creates an addref()-ed object. dosomethingwithfooandreturnittoo() leaks two refcounts. hmm...this probably isn't okay, es...
Scroll-linked effects
pi: use cases. these effects work well in browsers where the scrolling is done synchronously on the browser's main thread. however, most browsers now support some sort of asynchronous scrolling in order to provide a consistent 60 frames per second experience to the user. in the asynchronous scrolling model, the visual scroll position is updated in the compositor thread and is visible to the user before the scroll event is updated in the dom and fired on the main thread. this means that the effects implemented will lag a little bit behind what the user sees the scroll position to be. this can cause the effect to be laggy, janky, or jittery — in short, something we want to avoid. below are a couple of examples of effects that would not work well with asynchronous scrolling, along with equivale...
TraceMalloc
e existing allocations to a file by calling the function tracemallocdumpallocations from javascript. you can use the following web page to do so. <script type="text/javascript"> var filename = window.prompt("filename to log: "); if (filename) tracemallocdumpallocations(filename); </script> one can then use the script tools/trace-malloc/diffbloatdump.pl to compare trace-malloc dumps before and after doing an action that might leak. if there are significant differences, it might be worth examining the call stacks for the destructors of the objects in question to see what is extending their lifetime. (this can be done by examining the unprocessed output of an xpcom_mem_refcnt_log, one of the nstracerefcnt logs.) you should use the --use-address argument to diffbloatdump.pl, and then ...
ui.textSelectBackground
ui.textselectbackground saves the color in which the background of a text selection in the user interface or in content will be styled. ...
ui.textSelectForeground
ui.textselectforeground saves the color in which the text of a text selection in the user interface or the content will be styled. ...
Patches and pushes
etails. in the attachment details, select the ? from the dropdown menu next to the review flag. this will display a text box to assign the review to someone. enter :flod as the requestee. review, commit, & land address any review comments made by the reviewers and update the patch until it receives an r+ rating. if the r+ is "with nits" (i.e., that's short for nit-picky requests), fix those before committing. also, no new patch attachment will be needed. commit the patch to your aurora repo. only commit the changes you have reviewed. use a commit message that mentions the bug number, describes the change, and mentions the reviewer. for example: hg ci -m "bug 654321, copied the comment from the doc without reading, r=nobody" path-to-changed-files close the bug, copying t...
A guide to searching crash reports
the mozilla crash-stats site provides facilities for investigating large numbers of firefox crash reports. this guide to searching through crash reports may help you locate the crash reports that will help you find and fix the firefox bug you're working on. specifically, crash-stats offers two basic functions: searching you can search the crash reports database by over 100 criteria: crash signature, date, platform, product, version, etc. grouping you can cluster the results of each search into groups using the same criteria. to achieve full power and flexibility requires a good understanding of both of these functions. ...
L20n Javascript API
ze. ctx.localize(['hello', 'new'], function(l10n) { var node = document.queryselector('[data-l10n-id=hello]'); node.textcontent = l10n.entities.hello.value; node.classlist.remove('hidden'); }); ctx.registerlocales(defaultlocale: string?, availablelocales: array<string>?) register the default locale of the context instance, as well as all other locales available to the context instance before the language negotiation. locales are referenced by their bcp 47 language codes. ctx.registerlocales('en-us', ['ar', 'es-ar', 'es-es', 'en-us', 'fr', 'pl']); defaultlocale is the original language of the context instance and will be used as the last fallback locale if other locales are registered. if it is undefined, or if registerlocales hasn't been called at all, the context instance will ...
AsyncTestUtils extended framework
sometimes in your tes...
McCoy
this is in the form of the public part of a cryptographic key included in the original add-on you release. the first step is to create a cryptographic key. simply click the "create" toolbar button or select "create key" from the "keys" menu. you should giv...
About NSPR
in of approximately 12 hours. but in order to deal with the wrap-around issue, only half that namespace may be utilized. therefore, the minimal usable interval available from the timers is slightly less than six hours. calendar times are 64-bit signed numbers with units of microseconds. the epoch for calendar times is midnight, january 1, 1970, greenwich mean time. negative times extend to times before 1970, and positive numbers forward. use of 64 bits allows a representation of times approximately in the range of -30000 to the year 30000. there is a structural representation (i.e., exploded view), routines to acquire the current time from the host system, and convert them to and from the 64-bit and structural representation. additionally there are routines to convert to and from most well-know...
NSPR Contributor Guide
te 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 what may be a substantial effort in making a candidate feature for nspr, talk to us. we may tell you that you have a good idea; we may say that it really is not a good candidate for inclusion in nspr; we may give you suggestions on what would make it more generalized, hence a good candidate for inclusion in nspr. use bugzilla to track your work. be verbose. nspr wants you to document yo...
NSPR release procedure
nspr version in mozilla/nsprpub/pr/tests/vercheck.c. change the nspr version in mozilla/nsprpub/admin/repackage.sh. source tarball binary distributions right now i use the mozilla/nsprpub/admin/repackage.sh script to generate the binary distributions published on ftp.mozilla.org. as the name of the shell script implies, repackage.sh merely repackages binary distributions in a different format. before you run repackage.sh, you need to have built the binary distributions using the "gmake release" makefile target. these binary distributions are jar files, which are really zip files, and they are published in the directory /share/builds/components. this design comes from the netscape days. the repackage.sh script repackages the jar files into the form most commonly used on that platform. so on un...
Process Forking in NSPR
original document information author: alan o. freier last updated date: 1998 ...
I/O Functions
a file or directory in a file system is specified by its pathname. nspr uses unix-style pathnames, which are null-terminated character strings. only the ascii character set is supported. the forward slash (/) separates the directories in a pathname. nspr converts the slashes in a pathname to the directory separator of the native os--for example, backslash (\) on windows and colon (:) on mac os--before passing it to the native system calls. some file systems also differentiate drives or volumes. pr_open pr_delete pr_getfileinfo pr_getfileinfo64 pr_rename pr_access type praccesshow functions that act on file descriptors pr_close pr_read pr_write pr_writev pr_getopenfileinfo pr_getopenfileinfo64 pr_seek pr_seek64 pr_available pr_available64 pr_sync pr_getdesc...
Interval Timing
efines a platform-dependent type, printervaltime, for timing intervals of fewer than approximately 6 hours. this chapter describes printervaltime and the functions that allow you to use it for timing purposes: interval time type and constants interval functions interval time type and constants all timed functions in nspr require a parameter that depicts the amount of time allowed to elapse before the operation is declared failed. the type of such arguments is printervaltime. such parameters are common in nspr functions such as those used for i/o operations and operations on condition variables. nspr 2.0 provides interval times that are efficient in terms of performance and storage requirements. conceptually, they are based on free-running counters that increment at a fixed rate without p...
Linked Lists
ist, and for the nodes being added and removed from the list. ...
Logging
logging are: pr_newlogmodule pr_setlogfile pr_setlogbuffering pr_logprint pr_logflush pr_log_test pr_log pr_assert pr_assert pr_static_assert (new in nspr 4.6.6xxx this hasn't been released yet; the number is a logical guess) pr_not_reached use example the following sample code fragment demonstrates use of the logging and debugging aids. compile the program with debug defined. ...
NSPR LOG MODULES
you would be able to download the log file as an artifact from the log viewer. (other tests?) ...
Named Shared Memory
ch it when you're finished. pr_detachsharedmemory should be called to unmap the shared memory segment from the application's address space. pr_closesharedmemory should be called when no further use of the prsharedmemory object is required within a process. following a call to pr_closesharedmemory, the prsharedmemory object is invalid and cannot be reused. pr_deletesharedmemory should be called before process termination. after you call pr_deletesharedmemory, any further use of the shared memory associated with the name may cause unpredictable results. filenames the name passed to pr_opensharedmemory should be a valid filename for a unix platform. pr_opensharedmemory creates file using the name passed in. some platforms may mangle the name before creating the file and the shared memory. the ...
PRCallOnceType
ation process has been completed. inprogress if not zero, the initialization process is currently being executed. calling threads that observe this status block until inprogress is zero. status an indication of the outcome of the initialization process. description the client is responsible for initializing the prcalloncetype structure to all zeros. this initialization must be accomplished before any threading issues exist. ...
PRFileMap
type returned by pr_createfilemap and passed to pr_memmap and pr_closefilemap. syntax #include <prio.h> typedef struct prfilemap prfilemap; description the opaque structure prfilemap represents a memory-mapped file object. before actually mapping a file to memory, you must create a memory-mapped file object by calling pr_createfilemap, which returns a pointer to prfilemap. then sections of the file can be mapped into memory by passing the prfilemap pointer to pr_memmap. the memory-mapped file object is closed by passing the prfilemap pointer to pr_closefilemap. ...
PRLinger
buffer. syntax #include <prio.h> typedef struct prlinger { prbool polarity; printervaltime linger; } prlinger; fields the structure has the following fields: polarity polarity of the option's setting: pr_false means the option is off, in which case the value of linger is ignored. pr_true means the option is on, and the value of linger will be used to determine how long pr_close waits before returning. linger time (in printervaltime units) to linger before closing if any data remain in the socket send buffer. description by default, pr_close returns immediately, but if there are any data remaining in the socket send buffer, the system attempts to deliver the data to the peer. the pr_sockopt_linger socket option, with a value represented by a structure of type prlinger, makes it po...
PRNetAddr
6 member is equivalent to struct sockaddr_in6. (note that prnetaddr does not have the length field that is present in struct sockaddr_in on some unix platforms.) the macros pr_af_inet, pr_af_inet6, pr_inaddr_any, pr_inaddr_loopback are defined if prio.h is included. pr_inaddr_any and pr_inaddr_loopback are special ipv4 addresses in host byte order, so they must be converted to network byte order before being assigned to the inet.ip field. ...
PRThreadState
t function until another thread joins it. the join process permits strict synchronization of thread termination and therefore promotes effective resource management. if a thread is created as an unjoinable (also called detached) thread, it terminates and cleans up after itself after returning from its root function. this results in some ambiguity after the thread's root function has returned and before the thread has finished terminating itself. ...
PRTime
a representation of absolute times. syntax #include <prtime.h> typedef print64 prtime; description this type is a 64-bit integer representing the number of microseconds since the nspr epoch, midnight (00:00:00) 1 january 1970 coordinated universal time (utc). a time after the epoch has a positive value, and a time before the epoch has a negative value. in nspr, we use the more familiar term greenwich mean time (gmt) in place of utc. although utc and gmt are not exactly the same in their precise definitions, they can generally be treated as if they were. note: keep in mind that while prtime stores times in microseconds since epoch, javascript date objects store times in milliseconds since epoch. ...
PR_Accept
ous socket can still be used to accept more connections. if the addr parameter is not null, pr_accept stores the address of the connecting entity in the prnetaddr object pointed to by addr. pr_accept blocks the calling thread until either a new connection is successfully accepted or an error occurs. if the timeout parameter is not pr_interval_no_timeout and no pending connection can be accepted before the time limit, pr_accept returns null with the error code pr_io_timeout_error. ...
PR_AtomicSet
32 *val, print32 newval); parameters the function has the following parameter: val a pointer to the value to be set. newval the new value to assign to the val parameter. returns the function returns the prior value of the referenced variable. description pr_atomicset first reads the value of var, then updates it with the supplied value. the returned value is the value that was readbefore memory was updated. the memory modification is unconditional--that is, it isn't a test and set operation. ...
PR_AttachThread
tachthread automatically for the primordial thread. note: as of nspr release v3.0, pr_attachthread and pr_detachthread are obsolete. a native thread not created by nspr is automatically attached the first time it calls an nspr function, and automatically detached when it exits. in nspr release 19980529b and earlier, it is necessary for a native thread not created by nspr to call pr_attachthread before it calls any nspr functions, and call pr_detachthread when it is done calling nspr functions. ...
PR_CEnterMonitor
(so it has a value of one). if a match is found, then either the calling thread is already in the monitor (and this is a reentrant call) or another thread is holding the monitor's mutex. in the former case, the entry count is simply incremented and the function returns. in the latter case, the calling thread is likely to find the monitor locked by another thread and waits for that thread to exit before continuing. note: pr_centermonitor and pr_cexitmonitor must be paired--that is, there must be an exit for every entry--or the object will never become available for any other thread. ...
PR_CallOnce
from that time on, the client should consider the object read-only (or even opaque) and allow the runtime to manipulate its content appropriately. ...
PR_CreateIOLayerStub
the functions for the new layer. returns a new file descriptor for the specified layer. description a new layer may be allocated by calling pr_createiolayerstub. the file descriptor returned contains the pointer to the i/o methods table provided. the runtime neither modifies the table nor tests its correctness. the caller should override appropriate contents of the file descriptor returned before pushing it onto the protocol stack. ...
PR_CreateThread
orable machine-specific stack size. returns the function returns one of the following values: if successful, a pointer to the new thread. this pointer remains valid until the thread returns from its root function. if unsuccessful, (for example, if system resources are unavailable), null. description if you want the thread to start up waiting for the creator to do something, enter a lock before creating the thread and then have the thread's root function enter and exit the same lock. when you are ready for the thread to run, exit the lock. for more information on locks and thread synchronization, see introduction to nspr. if you want to detect the completion of the created thread, make it joinable. you can then use pr_jointhread to synchronize the termination of another thread. ...
PR_DestroyCondVar
destroys a condition variable. syntax #include <prcvar.h> void pr_destroycondvar(prcondvar *cvar); parameter pr_destroycondvar has one parameter: cvar a pointer to the condition variable object to be destroyed. description before calling pr_destroycondvar, the caller is responsible for ensuring that the condition variable is no longer in use. ...
PR_DestroyMonitor
destroys a monitor object. syntax #include <prmon.h> void pr_destroymonitor(prmonitor *mon); parameter the function has the following parameter: mon a reference to an existing structure of type prmonitor. description the caller is responsible for guaranteeing that the monitor is no longer in use before calling pr_destroymonitor. there must be no thread (including the calling thread) in the monitor or waiting on the monitor. ...
PR_DetachThread
y if you attached the thread using pr_attachthread. note: as of nspr release v3.0, pr_attachthread and pr_detachthread are obsolete. a native thread not created by nspr is automatically attached the first time it calls an nspr function, and automatically detached when it exits. in nspr release 19980529b and earlier, it is necessary for a native thread not created by nspr to call pr_attachthread before it calls any nspr functions, and call pr_detachthread when it is done calling nspr functions. ...
PR ImportTCPSocket
n use the native file descriptor successfully. for example, on posix systems, nspr will put the native file descriptor (an int) in non-blocking mode by calling fcntl to set the o_nonblock file status flag on the native file descriptor, and then nspr will call socket functions such as recv, send, and poll on the native file descriptor. the caller must not do anything to the native file descriptor before the pr_importtcpsocket call that will prevent the native file descriptor from working in non-blocking mode. warning in theory, code that uses pr_importtcpsocket may break when nspr's implementation changes. in practice, this is unlikely to happen because nspr's implementation has been stable for years and because of nspr's strong commitment to backward compatibility. using pr_importtcpsocket is...
PR_PushIOLayer
...
PR_QueueJob_Timer
.h> nspr_api(prjob *) pr_queuejob_timer( prthreadpool *tpool, printervaltime timeout, prjobfn fn, void * arg, prbool joinable ); parameters the function has the following parameters: tpool a pointer to a prthreadpool structure previously created by a call to pr_createthreadpool. iod a pointer to a prjobiodesc structure. timeout a value, expressed as a printervaltime, to wait before queuing the job. fn the function to be executed when the job is executed. arg a pointer to an argument passed to fn. joinable if pr_true, the job is joinable. if pr_false, the job is not joinable. see pr_joinjob. returns pointer to a prjob structure or null on error. ...
PR_SetThreadPrivate
-thread private data, or more likely, a pointer to the data. returns the function returns one of the following values: if successful, pr_success. if the index is invalid, pr_failure. description if the thread already has non-null private data associated with it, and if the destructor function for the index is known (not null), nspr calls the destructor function associated with the index before setting the new data value. the pointer at the index is swapped with null. if the swapped out value is not null, the destructor function is called. on return, the private data associated with the index is reassigned the new private data's value, even if it is null. the runtime provides no protection for the private data. the destructor is called with the runtime holding no locks. synchronization ...
PR_WaitForPollableEvent
syntax nspr_api(prstatus) pr_waitforpollableevent(prfiledesc *event); parameter the function has the following parameter: event pointer to a prfiledesc structure previously created via a call to pr_newpollableevent. returns the function returns one of the following values: if successful, pr_success. ...
PR_Write
n. the value -1 indicates that the operation failed. the reason for the failure is obtained by calling pr_geterror. description the thread invoking pr_write blocks until all the data is written or the write operation fails. therefore, the return value is equal to either amount (success) or -1 (failure). note that if pr_write returns -1, some data (less than amount bytes) may have been written before an error occurred. ...
PR_Writev
icates that the operation failed. the reason for the failure can be obtained by calling pr_geterror. description the thread calling pr_writev blocks until all the data is written or the write operation fails. therefore, the return value is equal to either the sum of all the buffer lengths (on success) or -1 (on failure). note that if pr_writev returns -1, part of the data may have been written before an error occurred. if the timeout parameter is not pr_interval_no_timeout and all the data cannot be written in the specified interval, pr_writev returns -1 with the error code pr_io_timeout_error. this is the type definition for priovec: typedef struct priovec { char *iov_base; int iov_len; } priovec; the priovec structure has the following fields: iov_base a pointer to the beginning...
NSPR API Reference
strdup pl_strfree floating point number to string conversion pr_strtod pr_dtoa pr_cnvtf long long (64-bit) integers bitmaps formatted printing linked lists linked list types prclist linked list macros pr_init_clist pr_init_static_clist pr_append_link pr_insert_link pr_next_link pr_prev_link pr_remove_link pr_remove_and_init_link pr_insert_before pr_insert_after dynamic library linking library linking types prlibrary prstaticlinktable library linking functions pr_setlibrarypath pr_getlibrarypath pr_getlibraryname pr_freelibraryname pr_loadlibrary pr_unloadlibrary pr_findsymbol pr_findsymbolandlibrary finding symbols defined in the main executable program platform notes ...
Building NSS
build environment nss needs a c and c++ compiler. it has minimal dependencies, including only standard c and c++ libraries, plus zlib. for building, you also need make. ideally, also install gyp and ninja and put them on your path. ...
NSS Certificate Download Specification
ported in text form. the text form begins with the following line: -----begin certificate----- following this line should be the certificate data, which can be in any of the binary formats described above. this data must be base64 encoded as described by rfc 1113. following the data should be the following line: -----end certificate----- in a text format download, nss ignores any text before the first begin certificate line, and ignores any text after the first end certificate line. between those two lines, there must be exactly one item of any of the supported binary formats described above, and that one item must be base64 encoded. regardless of which of the supported binary formats is used, the begin and end lines must say certificate, and not any other word (such as key). the beg...
Encrypt Decrypt MAC Keys As Session Objects
e) { pr_close(encfile); } if (slot) { pk11_freeslot(slot); } if (enckey) { pk11_freesymkey(enckey); } if (mackey) { pk11_freesymkey(mackey); } return rv; } /* * this example illustrates basic encryption/decryption and macing * generates the encryption/mac keys and uses token for storing. * encrypts the input file and appends mac before storing in intermediate * header file. * writes the cka_ids of the encryption keys into intermediate header file. * reads the intermediate headerfile for cka_ids and encrypted * contents and decrypts into output file. */ int main(int argc, char **argv) { secstatus rv; secstatus rvshutdown; pk11slotinfo *slot = null; ploptstate *optstate; ...
Encrypt and decrypt MAC using token
e) { pr_close(encfile); } if (slot) { pk11_freeslot(slot); } if (enckey) { pk11_freesymkey(enckey); } if (mackey) { pk11_freesymkey(mackey); } return rv; } /* * this example illustrates basic encryption/decryption and macing * generates the encryption/mac keys and uses token for storing. * encrypts the input file and appends mac before storing in intermediate * header file. * writes the cka_ids of the encryption keys into intermediate header file. * reads the intermediate headerfile for cka_ids and encrypted * contents and decrypts into output file. */ int main(int argc, char **argv) { secstatus rv; secstatus rvshutdown; pk11slotinfo *slot = null; ploptstate *optstate; ...
FIPS Mode - an explanation
ifficult 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 mode, every user must have a good strong "master password", and must enter it each time he starts or restarts firefox before he can visit any web sites that use cryptography (https). firefox can only use the latest version of ssl, known 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 m...
HTTP delegation
tion will provide the results in its "out parameters". please read the source code documentation to learn how to use this api synchronously or asynchronously. now that we have explained the interaction between nss, the callback functions and the application, let's look at the steps required by the application to initially register the callbacks. make sure you have completed the nss initialization before you attempt to register the callbacks. look at sec_httpclientfcn, which is a (versioned) table of function pointers. create an instance of this type and supply a pointer to your implementation for each entry in the function table. finally register your http client implementation with a call to sec_registerdefaulthttpclient. ...
HTTP delegation
tion will provide the results in its "out parameters". please read the source code documentation to learn how to use this api synchronously or asynchronously. now that we have explained the interaction between nss, the callback functions and the application, let's look at the steps required by the application to initially register the callbacks. make sure you have completed the nss initialization before you attempt to register the callbacks. look at sec_httpclientfcn, which is a (versioned) table of function pointers. create an instance of this type and supply a pointer to your implementation for each entry in the function table. finally register your http client implementation with a call to sec_registerdefaulthttpclient. ...
4.3.1 Release Notes
ut restriction, whether or not the peer's client hello bears the renegotiation info extension (like we always did in the past). sslsocket.ssl_renegotiate_requires_xtn - not yet implemented explicitly set the key usage for the generated private key in pkcs #11, each keypair can be marked with the operations it will be used to perform. some tokens require that a key be marked for an operation before the key can be used to perform that operation; other tokens don't care. nss/jss provides a way to specify a set of flags and a corresponding mask for these flags. see generateeckeypairwithopflags see generatersakeypairwithopflags see generatedsakeypairwithopflags distribution information jss is checked into mozilla/security/jss/. the cvs tag for the jss 4.3.1 release is jss_4_3_1_rtm. s...
Build instructions for JSS 4.3.x
install a java compiler and runtime. jss supports java version 1.5 or later. we suggest you use the latest. you must have perl version 5.005 or later. now you are ready to build jss. follow these steps: switch to the appropriate directory and check out jss from the root of your source tree. ...
JSS
Mozilla › Projects › NSS › JSS
to be used. a current limitation to the configured sunpkcs11-nss bridge configuration is if you add a pkcs#11 module to the nss database such as for a smartcard, you won't be able to access that smartcard through the sunpkcs11-nss bridge. if you use jss, you can easily get lists of modules and tokens that are configured in the nss db and freely access all of it. documentation before you use jss, you should have a good understanding of the crypto technologies it uses. you might want to read these documents: introduction to public-key cryptography. explains the basic concepts of public-key cryptography that underlie nss and jss. introduction to ssl. introduces the ssl protocol, including information about cryptographic ciphers supported by ssl and the steps inv...
NSS 3.14.2 release notes
usage_ctl_signing notable changes in nss 3.14.2 bug 805604 - support for aes-ni and avx accelerated aes-gcm was contributed by shay gueron of intel. if compiled on linux systems in 64-bit mode, nss will include runtime detection to check if the platform supports aes-ni and pclmulqdq. if so, nss uses the optimized code path, reducing the cpu cycles per byte to 1/20 of what was required before the patch (https://bugzilla.mozilla.org/show_bug.cgi?id=805604 and https://crypto.stanford.edu/realworldcrypto/slides/gueron.pdf). support for other platforms, such as windows, will follow in a future nss release. (https://bugzilla.mozilla.org/show_bug.cgi?id=540986) sqlite has been updated to 3.7.15. note: please apply the patch in https://bugzilla.mozilla.org/show_bug.cgi?id=837799 if you bui...
NSS 3.15.2 release notes
use the sha-256 prf bug 663313 - md2, md4, and md5 signatures are no longer accepted for ocsp or crls, consistent with their handling for general certificate signatures. bug 884178 - add pk11_cipherfinal macro bugs fixed in nss 3.15.2 bug 734007 - sizeof() used incorrectly bug 900971 - nssutil_readsecmoddb() leaks memory bug 681839 - allow ssl_handshakenegotiatedextension to be called before the handshake is finished. bug 848384 - deprecate the ssl cipher policy code, as it's no longer relevant. it is no longer necessary to call nss_setdomesticpolicy because all cipher suites are now allowed by default. a complete list of all bugs resolved in this release can be obtained at https://bugzilla.mozilla.org/buglist.cgi?resolution=fixed&classification=components&query_format=advanced&ta...
NSS 3.16.2.3 release notes
in sslerr.h ssl_error_inappropriate_fallback_alert - a new ssl error code. in sslproto.h tls_fallback_scsv - a a signaling cipher suite value that indicates a handshake is the result of tls version fallback. notable changes in nss 3.16.2.3 bug 1057161: check that an imported elliptic curve public key is valid. previously nss would only validate the peer's public key before performing ecdh key agreement. now ec public keys are validated at import time. bugs fixed in nss 3.16.2.3 bug 1057161 - nss hangs with 100% cpu on invalid ec key bug 1036735 - add support for draft-ietf-tls-downgrade-scsv to nss compatibility nss 3.16.2.3 shared libraries are backward compatible with all older nss 3.x shared libraries. a program linked with older nss 3.x shared librarie...
NSS 3.17.2 release notes
bugs. notable changes in nss 3.17.2 bug 1049435: change rsa_privatekeycheck to not require p > q. this fixes a regression introduced in nss 3.16.2 that prevented nss from importing some rsa private keys (such as in pkcs #12 files) generated by other crypto libraries. bug 1057161: check that an imported elliptic curve public key is valid. previously nss would only validate the peer's public key before performing ecdh key agreement. now ec public keys are validated at import time. bug 1078669: certutil crashes when an argument is passed to the --certversion option. bugs fixed in nss 3.17.2 this bugzilla query returns all the bugs fixed in nss 3.17.2: https://bugzilla.mozilla.org/buglist.cgi?resolution=fixed&classification=components&query_format=advanced&product=nss&target_milestone=3.17.2 co...
NSS 3.28.1 release notes
:de:dc:ea:08:e7:da:aa:07:81:5f:f0 the version number of the updated root ca list has been set to 2.11 a misleading assertion/alert has been removed, when nss tries to flush data to the peer but the connection was already reset. bugs fixed in nss 3.28.1 bug 1296697 - december 2016 batch of root ca changes bug 1322496 - internal error assert when the other side closes connection before reading eoed compatibility nss 3.28.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.28.1 shared libraries without recompiling or relinking. furthermore, applications that restrict their use of nss apis to the functions listed in nss public functions will remain compatible with future ve...
NSS 3.44 release notes
c 1540205 - freebl build fails with -dnss_disable_chachapoly 1532312 - post-handshake auth doesn't interoperate with openssl 1542741 - certutil -f crashes with segmentation fault 1546925 - allow preceding text in try comment 1534468 - expose chacha20 primitive 1418944 - quote cc/cxx variables passed to nspr 1543545 - allow to build nss as a static library 1487597 - early data that arrives before the handshake completes can be read afterwards 1548398 - freebl_gtest not building on linux/mac 1548722 - fix some coverity warnings 1540652 - softoken/sdb.c: logically dead code 1549413 - android log lib is not included in build 1537927 - ipsec usage is too restrictive for existing deployments 1549608 - signature fails with dbm disabled 1549848 - allow building nss for ios using gyp 1549...
NSS 3.47 release notes
t set bug 1583068 - nss 3.47 should pick up fix from bug 1575821 (nspr 4.23) bug 1152625 - support aes hw acceleration on armv8 bug 1549225 - disable dsa signature schemes for tls 1.3 bug 1586947 - pk11_importandreturnprivatekey does not store nickname for ec keys bug 1586456 - unnecessary conditional in pki3hack, pk11load and stanpcertdb bug 1576307 - check mechanism param and param length before casting to mechanism-specific structs bug 1577953 - support longer (up to rfc maximum) hkdf outputs bug 1508776 - remove refcounting from sftk_freesession (cve-2019-11756) bug 1494063 - support tls exporter in tstclnt and selfserv bug 1581024 - heap overflow in nss utility "derdump" bug 1582343 - soft token mac verification not constant time bug 1578238 - handle invald tag sizes for ckm_aes...
NSS 3.52 release notes
12493 - integrate avx2 chacha20, poly1305, and chacha20poly1305 from hacl*. bugs fixed in nss 3.52 bug 1633498 - fix unused variable 'getauxval' error on ios compilation. bug 1630721 - add softoken functions for fips. bug 1630458 - fix problem of gyp msvc builds not producing debug symbol files. bug 1629663 - add ikev1 quick mode kdf. bug 1629661 - mpconfig calls in ssl initialize policy before nss is initialized. bug 1629655 - support temporary session objects in ckfw. bug 1629105 - add pkcs11 v3.0 functions to module debug logger. bug 1626751 - fix error in generation of fuzz32 docker image after updates. bug 1625133 - fix implicit declaration of function 'getopt' error. bug 1624864 - allow building of gcm-arm32-neon on non-armv7 architectures. bug 1624402 - fix compilation erro...
NSS 3.53 release notes
22033) to disable that deprecation in order to use the algorithm. algorithms marked as deprecated will ultimately be removed. several root certificates in the mozilla program now set the cka_nss_server_distrust_after attribute, which nss consumers can query to further refine trust decisions. (bug 1618404, bug 1621159) if a builtin certificate has a cka_nss_server_distrust_after timestamp before the sct or notbefore date of a certificate that builtin issued, then clients can elect not to trust it. this attribute provides a more graceful phase-out for certificate authorities than complete removal from the root certificate builtin store. bugs fixed in nss 3.53 bug 1640260 - initialize pbe params (asan fix) bug 1618404 - set cka_nss_server_distrust_after for symantec root ...
Encrypt Decrypt_MAC_Using Token
) { pr_close(encfile); } if (slot) { pk11_freeslot(slot); } if (enckey) { pk11_freesymkey(enckey); } if (mackey) { pk11_freesymkey(mackey); } return rv; } /* * this example illustrates basic encryption/decryption and macing. * generates the encryption/mac keys and uses token for storing. * encrypts the input file and appends mac before storing in intermediate * header file. * writes the cka_ids of the encryption keys into intermediate header file. * reads the intermediate headerfile for cka_ids and encrypted * contents and decrypts into output file. */ int main(int argc, char **argv) { secstatus rv; secstatus rvshutdown; pk11slotinfo *slot = null; ploptstate *optstate; ...
NSS Sample Code Sample_3_Basic Encryption and MACing
) { pr_close(encfile); } if (slot) { pk11_freeslot(slot); } if (enckey) { pk11_freesymkey(enckey); } if (mackey) { pk11_freesymkey(mackey); } return rv; } /* * this example illustrates basic encryption/decryption and macing. * generates the encryption/mac keys and uses token for storing. * encrypts the input file and appends mac before storing in intermediate * header file. * writes the cka_ids of the encryption keys into intermediate header file. * reads the intermediate header file for cka_ids and encrypted * contents and decrypts into output file. */ int main(int argc, char **argv) { secstatus rv; secstatus rvshutdown; pk11slotinfo *slot = null; ploptstate *optstate; ...
NSS Sample Code Utilities_1
name = pk11_gettokenname(slot); if (tokenname) { tokenlen = port_strlen(tokenname); } } i = 0; do { int startphrase = i; int phraselen; /* handle the windows eol case */ while (phrases[i] != '\r' && phrases[i] != '\n' && i < nb) i++; /* terminate passphrase */ phrases[i++] = '\0'; /* clean up any eol before the start of the next passphrase */ while ( (i<nb) analyze="" char="" current="" getmodulepassword="" if="" int="" now="" passphrase="" phrase="&amp;phrases[startphrase];" phraselen="" pk11slotinfo="" pwdata="=" pwdata-="" retry="" return="" secupwdata="" the="" void="" while="">source != pw_none) { pr_fprintf(pr_stderr, "incorrect password/pin entered.\n"); return null; ...
NSS Sample Code sample2
buf1 len must be atleast (data len + 8) */ tmp1_outlen = tmp2_outlen = 0; /* create cipher context */ enccontext = pk11_createcontextbysymkey(ciphermech, cka_encrypt, symkey, secparam); rv1 = pk11_cipherop(enccontext, buf1, &tmp...
NSS Sample Code sample6
nss sample code 6: persistent symmetric keys in nss database /* example code to illustrate generation of a secret symmetric key ring * that persists in the nss database. the symmetric keys can then be used * without ever exposing them in the clear. * * to encrypt, you need the id of the key to use. * to decrypt, you need the ciphertext and the id of the key that was used * to encrypt * * before running this example, create the nss database * certutil -n -d . * (enter "test" when prompted for password) */ #include "nss.h" #include "pk11pub.h" /* the key id can be any sequence of bytes. this example happens to use an * integer */ void genkey(int id); /* this callback is responsible for returning the password to the nss * key database. for example purposes, this function hardc...
EncDecMAC using token object - sample 3
close(infile); } if (headerfile) { pr_close(headerfile); } if (encfile) { pr_close(encfile); } if (slot) { pk11_freeslot(slot); } if (enckey) { pk11_freesymkey(enckey); } if (mackey) { pk11_freesymkey(mackey); } return rv; } /* * this example illustrates basic encryption/decryption and macing * generates the encryption/mac keys and uses token for storing. * encrypts the input file and appends mac before storing in intermediate * header file. * writes the cka_ids of the encryption keys into intermediate header file. * reads the intermediate headerfile for cka_ids and encrypted * contents and decrypts into output file. */ int main(int argc, char **argv) { secstatus rv; secstatus rvshutdown; pk11slotinfo *slot = null; ploptstate *optstate; ploptstatus status; char headerfilename[50]; char encrypted...
Utilities for nss samples
name = pk11_gettokenname(slot); if (tokenname) { tokenlen = port_strlen(tokenname); } } i = 0; do { int startphrase = i; int phraselen; /* handle the windows eol case */ while (phrases[i] != '\r' && phrases[i] != '\n' && i < nb) i++; /* terminate passphrase */ phrases[i++] = '\0'; /* clean up any eol before the start of the next passphrase */ while ( (i<nb) && (phrases[i] == '\r' || phrases[i] == '\n')) { phrases[i++] = '\0'; } /* now analyze the current passphrase */ phrase = &phrases[startphrase]; if (!tokenname) break; if (port_strncmp(phrase, tokenname, tokenlen)) continue; phraselen = port_strlen(phrase); if...
NSS sources building testing
ectory, e.g., using the ld_library_path or dyld_library_path environment variable. running the nss test suite this is an important part of development work, in order to ensure your changes don't introduce regressions. when adding new features to nss, tests for the new feature should be added as well. you must build nss prior to running the tests. after the build on your computer has succeeded, before you can run the tests on your computer, it might be necessary to set additional environment variables. the nss tests will start tcp/ip server tools on your computer, and in order for that to work, the nss test suite needs to know which hostname can be used by client tools to connect to the server tools. on machines that are configured with a hostname that has been registered in your network's dns...
nss tech note1
that includes both der (distinguished encoding rules) and ber (basic encoding rules).† it handles both streaming and non-streaming input. the "quickder" decoder, written by julien pierre for nss 3.6 . this decoder was written when performance issues were discovered with the classic decoder. it can only decode der .† it does not handle streaming input, and requires that all input be present before beginning to decode. despite their differences, the two decoders have a lot in common. quickder was written to be as compatible as possible with the classic decoder, in order to ease migration to it in areas of critical performance bottlenecks. for this reason, i will first describe all the common functionality of the two decoders, before outlining their differences. the main non-streaming api...
nss tech note8
sec->uncache = ssl_sid_uncache; which are functions defined in sslsnce.c, the server session cache source file. for clients these pointers point to sec->cache = cachesid; sec->uncache = lockanduncachesid; which are functions defined in sslnonce.c, the client session cache source file. the same cache/uncache api is used by both client and server code. as originally designed, before calling the cache function, the caller was responsible to fill in the session creation time (which might not be the same as the time of insertion into the cache) and the session expiration time, among other things. since nss 1.0, up until nss 3.4, there were two global variables that contained the expected session lifetimes for ssl2 and ssl3 sessions. extern pruint32 ssl_sid_timeout; (the ss...
NSS Tools sslstrength
command. the second form attempts to connect to the named ssl host. the hostname argument must be present. however, the port number is an optional argument, and if not given, will default to the https port (443). restricting ciphers by default, sslstrength assumes that all the preferences are on, so it will use any preferences in your policy. the enabled ciphersuites will always be printed out before the connection is made. if you want to test out a particular cipher, there are two ways to affect which ciphers are available. firstly, you can set policy to be either domestic or export. this restricts the available ciphers to the same set used by communicator. in addition to this, the ciphers command can be used to further restrict the ciphers available. the argument to the ciphers command is a...
Notes on TLS - SSL 3.0 Intolerant Servers
etcraft.com/site_report?url= to the beginning of the url. the server software will appear next to server under ssl certificate information. for instance, to check https://bugzilla.mozilla.org/, then visit http://toolbar.netcraft.com/site_rep...a.mozilla.org/. add the information on such a server (software, url) to bug 59321 at bugzilla. (note: you will be asked to provide your email address before you can file a bug at bugzilla.) original document information author : katsuhiko momoi last updated date: january 27th, 2003 copyright © 2001-2003 netscape. all rights reserved. ...
PKCS #11 Module Specs
ly logged in. rootflags - comma separated of flags describing any root certs that may be stored (case-insensitive). valid flags are: hasrootcerts - claims that this token has the default root certs and trust values. at init time nss, will try to look for a default root cert device if one has not already been loaded. hasroottrust - parsed but ignored. timeout - time in minutes before the current authentication should be rechecked. this value is only used if askpwd is set to 'timeout'. (default = 0). askpwd - case-insensitive flag describing how password prompts should be manages. only one of the following can be specified. every - prompt whenever the a private key on this token needs to be access (this is on the entire token, not on a key-by-key basis. timeout- wh...
PKCS11 Implement
s simultaneously and if you wish to support c_initpin, c_setpin, or c_generatekeypair, you must support simultaneous read-only and read/write sessions. random-number generation and simple digesting the nss requires that the following functions operate without authenticating to the token: c_seedrandom, c_generaterandom, and c_digest (for sha, md5, and md2). if your token requires authentication before executing these functions, your token cannot provide the default implementation for them. (you can still use your token for other default functions.) nss does not support replacement of default functions. later versions will provide such support. read/write and read-only requirements the nss assumes that the following operations always require a read/write session: creating a token object, s...
Build instructions
. cd nss gmake nss_build_all the output of the build will be in the dist directory alongside the nspr and nss directories. for information on troubleshooting the build system, see troubleshooting nss and jss build systems. build instructions for older versions (cvs) set the environment variable cvsroot to :pserver:anonymous@cvs-mirror.mozilla.org:/cvsroot cvs login (if you haven't before). check out nspr and nss: cvs co -r nspr_4_9_5_rtm nspr cvs co -r nss_3_14_2_rtm nss set environment variables as described in the mercurial-based instructions. cd mozilla/security/nss gmake nss_build_all the output of the build will be in mozilla/dist subdirectory. for information on troubleshooting the build system, see troubleshooting nss and jss build systems. ...
FC_CopyObject
t ); parameters hsession [in] session handle. hobject [in] object handle. ptemplate [in] object template. uscount [in] number of attributes in the template. phnewobject [out] pointer to location to receive the new object's handle. description fc_copyobject creates a copy of an object using the attributes specified in the template. a user must log into the token (to assume the nss user role) before copying a secret or private key object. return value examples see also fc_destroyobject, nsc_copyobject ...
FC_CreateObject
ulcount, ck_object_handle_ptr phobject ); parameters hsession [in] session handle. ptemplate [in] object template. ulcount [in] number of attributes in the template. phobject [out] pointer to location to receive the new objects handle. description fc_createobject creates an object using the attributes specified in the template. a user must log into the token (to assume the nss user role) before calling fc_createobject. return value examples see also fc_destroyobject, nsc_createobject ...
FC_Decrypt
ock. usencrypteddatalen [in] length of the data in bytes. pdata [out] pointer to location where recovered data is to be stored. pusdatalen [in,out] pointer to location where the length of recovered data is to be stored. description fc_decrypt decrypts a block of data according to the attributes of the previous call to fc_decryptinit. a user must log into the token (to assume the nss user role) before calling fc_decrypt. return value examples see also fc_decryptinit, nsc_decrypt ...
FC_DecryptDigestUpdate
pointer to the length of the recovered part buffer. description fc_decryptdigestupdate continues a multi-part decrypt and digest operation. after calling both fc_decryptinit and fc_digestinit to set up the operations this function may be called multiple times. the operation is finished by calls to fc_digestfinal and fc_decryptfinal. a user must log into the token (to assume the nss user role) before calling fc_decryptdigestupdate. return value examples see also nsc_decryptdigestupdate ...
FC_DecryptFinal
session [in] session handle. plastpart [out] pointer to the location where the last block of recovered data, if any, is to be stored. puslastpartlen [in,out] pointer to location where the number of bytes of recovered data is to be stored. description fc_decryptfinal returns the last block of data of a multi-part decryption operation. a user must log into the token (to assume the nss user role) before calling fc_decryptfinal. return value examples see also fc_decryptinit, nsc_decryptfinal ...
FC_DecryptInit
return value examples see also nsc_decryptinit ...
FC_DecryptUpdate
to location where recovered block is to be stored. puspartlen [in,out] pointer the location where the number of bytes of recovered data is to be stored. description fc_decryptupdate decrypts a block of data according to the attributes of the previous call to fc_decryptinit. the block may be part of a multi-part decryption operation. a user must log into the token (to assume the nss user role) before calling fc_decryptupdate. return value examples see also fc_decryptinit, nsc_decryptupdate ...
FC_DecryptVerifyUpdate
of the recovered part buffer. description fc_decryptverifyupdate continues a multi-part decryption and and signature verification operation. after calling both fc_decryptinit and fc_verifyinit to set up the operations this function may be called multiple times. the operation is finished by calls to fc_decryptfinal and fc_verifyfinal. a user must log into the token (to assume the nss user role) before calling fc_decryptverifyupdate. return value examples see also nsc_decryptverifyupdate ...
FC_DeriveKey
base key. pwrappedkey [in] pointer to the wrapped key. ptemplate [in] pointer to the list of attributes for the new key. usattributecount [in] number of attributes in the template. phkey [out] pointer to the location to receive the handle of the new key. description fc_derivekey derives (decrypts) a key and creates a new key object. a user must log into the token (to assume the nss user role) before calling fc_derivekey. return value examples see also nsc_derivekey ...
FC_DestroyObject
name fc_destroyobject - destroy an object. syntax ck_rv fc_destroyobject( ck_session_handle hsession, ck_object_handle hobject ); parameters hsession [in] session handle. hobject [in] object handle. description fc_destroyobject destroys an object. a user must log into the token (to assume the nss user role) before destroying a secret or private key object. return value examples see also nsc_destroyobject ...
FC_DigestEncryptUpdate
ength of the encrypted part buffer. description fc_digestencryptupdate continues a multi-part digest and encryption operation. after calling both fc_digestinit and fc_encryptinit to set up the operations this function may be called multiple times. the operation is finished by calls to fc_digestfinal and fc_encryptfinal in that order. a user must log into the token (to assume the nss user role) before calling fc_digestencryptupdate. return value examples see also nsc_digestencryptupdate ...
FC_DigestKey
digestkey( ck_session_handle hsession, ck_object_handle hkey ); parameters hsession [in] session handle. hkey [in] handle of the key to be digested. description fc_digestkey continues a multi-part digest operation by digesting the value of a secret key. the digest for the entire message is returned by a call to fc_digestfinal. a user must log into the token (to assume the nss user role) before calling fc_digestkey. return value examples see also fc_digestinit, fc_digestfinal, nsc_digestkey ...
FC_Encrypt
ndle. pdata [in] pointer to the data buffer usdatalen [in] length of the data buffer in bytes. pencrypteddata [out] pointer to location where encrypted data is to be stored. pusencrypteddatalen [in/out] number of bytes. description fc_encrypt encrypts a block of data according to the attributes of the previous call to fc_encryptinit. a user must log into the token (to assume the nss user role) before calling fc_encrypt. return value examples see also fc_encryptinit, nsc_encrypt ...
FC_EncryptFinal
on handle. plastencryptedpart [out] pointer to the location that receives the last encrypted data part, if any puslastencryptedpartlen [in,out] pointer to location where the number of bytes of the last encrypted data part is to be stored. description fc_encryptfinal returns the last block of data of a multi-part encryption operation. a user must log into the token (to assume the nss user role) before calling fc_encryptfinal. return value examples see also fc_encryptinit, nsc_encryptfinal ...
FC_EncryptInit
session, ck_mechanism_ptr pmechanism, ck_object_handle hkey ); parameters hsession[in] handle to the session. pmechanism[in] pointer to the mechanism to be used for subsequent encryption. hkey[in] handle of the encryption key. description fc_encryptinit initializes an encryption operation with the mechanism and key to be used. a user must log into the token (to assume the nss user role) before calling fc_encryptinit. return value ckr_ok slot information was successfully copied. ckr_slot_id_invalid the specified slot number is out of the defined range of values. examples see also nsc_encryptinit ...
FC_EncryptUpdate
ation where encrypted block is to be stored. pusencryptedpartalen [out] pointer the location where the number of bytes of encrypted data is to be stored. description fc_encryptupdate encrypts a block of data according to the attributes of the previous call to fc_encryptinit. the block may be part of a multi-part encryption operation. a user must log into the token (to assume the nss user role) before calling fc_encryptupdate. return value examples see also fc_encryptinit, nsc_encryptupdate ...
FC_FindObjectsInit
); parameters hsession [in] session handle. ptemplate [in] pointer to template. uscount [in] number of attributes in the template. description fc_findobjectsinit sets the attribute list for an object search. if fc_findobjectsinit is successful fc_findobjects may be called one or more times to retrieve handles of matching objects. a user must log into the token (to assume the nss user role) before searching for secret or private key objects. return value examples see also fc_findobjects, nsc_findobjectsinit ...
FC_GenerateKey
ism [in] pointer to the mechanism to use. ptemplate [in] pointer to the template for the new key. ulcount [in] number of attributes in the template. phkey [out] pointer to the location to receive the handle of the new key. description fc_generatekey generates a secret key, creating a new key object. the handle of new key is returned. a user must log into the token (to assume the nss user role) before calling fc_generatekey. return value examples see also nsc_generatekey ...
FC_GenerateKeyPair
n the private key template. phpublickey [out] pointer to the location to receive the handle of the new public key. phprivatekey [out] pointer to the location to receive the handle of the new private key. description fc_generatekeypair generates a public/private key pair, creating new key objects. the handles of new keys are returned. a user must log into the token (to assume the nss user role) before calling fc_generatekeypair. return value examples see also nsc_generatekeypair ...
FC_GetAttributeValue
on, ck_object_handle hobject, ck_attribute_ptr ptemplate, ck_ulong uscount ); parameters hsession [in] session handle. hobject [in] object handle. ptemplate [in, out] pointer to template. uscount [in] number of attributes in the template. description fc_getattributevalue gets the value of one or more attributes of an object. a user must log into the token (to assume the nss user role) before getting the attribute values of a secret or private key object. return value examples see also nsc_getattributevalue ...
FC_GetObjectSize
y of an object. syntax ck_rv fc_getobjectsize( ck_session_handle hsession, ck_object_handle hobject, ck_ulong_ptr pussize ); parameters hsession [in] session handle. hobject [in] object handle. pussize [out] pointer to location to receive the object's size. description fc_getobjectsize gets the size of an object in bytes. a user must log into the token (to assume the nss user role) before getting the size of a secret or private key object. return value examples see also nsc_getobjectsize ...
FC_InitToken
ers fc_inittoken() has the following parameters: slotid the id of the token's slot ppin the password of the security officer (so) ulpinlen the length in bytes of the so password plabel points to the label of the token, which must be padded with spaces to 32 bytes and not be null-terminated description fc_inittoken() initializes a brand new token or re-initializes a token that was initialized before. specifically, fc_inittoken() initializes or clears the key database, removes the password, and then marks all the user certs in the certificate database as non-user certs. (user certs are the 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 p...
FC_SetAttributeValue
ue( ck_session_handle hsession, ck_object_handle hobject, ck_attribute_ptr ptemplate, ck_ulong uscount ); parameters hsession [in] session handle. hobject [in] object handle. ptemplate [in, out] pointer to template. uscount [in] number of attributes in the template. description fc_setattributevalue sets the value of one or more attributes of an object. a user must log into the token before setting the attribute values of a secret or private key object. return value examples see also nsc_setattributevalue ...
FC_SetPIN
return value ckr_ok examples see also nsc_setpin ...
FC_Sign
[out] pointer to location where recovered data is to be stored. pussignaturelen [in, out] pointer to the maximum size of the output buffer, replaced by the length of the signature if the operation is successful. description fc_sign signs a message in a single operation according to the attributes of the previous call to fc_signinit. a user must log into the token (to assume the nss user role) before calling fc_sign. return value examples see also fc_signinit, nsc_sign ...
FC_SignEncryptUpdate
pointer to the length of the encrypted part buffer. description fc_signencryptupdate continues a multi-part signature and encryption operation. after calling both fc_signinit and fc_encryptinit to set up the operations this function may be called multiple times. the operation is finished by calls to fc_signfinal and fc_encryptfinal. a user must log into the token (to assume the nss user role) before calling fc_signencryptupdate. return value examples see also nsc_signencryptupdate ...
FC_SignFinal
nter to location containing the maximum buffer size. description fc_signfinal finishes a multi-part signing operation by returning the complete signature and clearing the operation context. if psignature is null the length of the signature is returned and fc_signfinal may be called again with psignature set to retrieve the signature. a user must log into the token (to assume the nss user role) before calling fc_signfinal. return value examples see also fc_signupdate, nsc_signfinal ...
FC_SignInit
return value examples see also nsc_signinit fc_sign fc_signupdate fc_signfinal ...
FC_SignRecover
return value examples see also nsc_signrecover ...
FC_SignRecoverInit
nism_ptr pmechanism, ck_object_handle hkey ); parameters hsession [in] session handle. pmechanism [in] mechanism to be used for the signing operation. hkey [in] handle of the key to be used. description fc_signrecoverinit initializes a initializes a signature operation where the (digest) data can be recovered from the signature. a user must log into the token (to assume the nss user role) before calling fc_signrecoverinit. return value examples see also nsc_signrecoverinit ...
FC_SignUpdate
[in] session handle. ppart [in] pointer to the next block of the data to be signed. uspartlen [in] length of data block in bytes. description fc_signupdate starts or continues a multi-part signature operation. one or more blocks may be part of the signature. the signature for the entire message is returned by a call to fc_signfinal. a user must log into the token (to assume the nss user role) before calling fc_signupdate. return value examples see also fc_signinit, fc_signfinal, nsc_signupdate ...
FC_UnwrapKey
e. phkey [out] pointer to the location to receive the handle of the unwrapped key. description fc_unwrapkey unwraps (decrypts) a key and creates a new key opbject. if pwrappedkey is null the length of the wrapped key is returned in puswrappedkeylen and fc_unwrapkey may be called again with pwrappedkey set to retrieve the wrapped key. a user must log into the token (to assume the nss user role) before calling fc_unwrapkey. return value examples see also nsc_unwrapkey ...
FC_Verify
parameters hsession [in] session handle. pdata [in] pointer to data block. usdatalen [in] length of the data in bytes. psignature [in] pointer to the signature. ussignaturelen [in] length of the signature in bytes. description fc_verify verifies a signature in a single-part operation, where the signature is an appendix to the data. a user must log into the token (to assume the nss user role) before calling fc_verify. return value ckr_ok is returned on success. ckr_signature_invalid is returned for signature mismatch. examples see also fc_verifyinit, nsc_verify ...
FC_VerifyFinal
ssion_handle hsession, ck_byte_ptr psignature, ck_ulong ussignaturelen ); parameters hsession [in] session handle. psignature [in] pointer to the buffer which will receive the digest or null. ussignaturelen [in] length of the signature in bytes. description fc_verifyfinal finishes a multi-part signature verification operation. a user must log into the token (to assume the nss user role) before calling fc_verifyfinal. return value examples see also fc_verifyupdate, nsc_verifyfinal ...
FC_VerifyInit
dle hsession, ck_mechanism_ptr pmechanism, ck_object_handle hkey ); parameters hsession [in] session handle. pmechanism [in] mechanism to be used for the verification operation. hkey [in] handle of the key to be used. description fc_verifyinit initializes a verification operation where the signature is an appendix to the data. a user must log into the token (to assume the nss user role) before calling fc_verifyinit. return value examples see also nsc_verifyinit ...
FC_VerifyRecover
n, out] pointer to the size of the output buffer, replaced by the length of the signature if the operation is successful. description fc_verifyrecover verifies data in a single operation where the (digest) data can be recovered from the signature. if psignature is null only the length of the signature is returned in *pussignaturelen. a user must log into the token (to assume the nss user role) before calling fc_verifyrecover. return value examples see also nsc_verifyrecover ...
FC_VerifyRecoverInit
ck_mechanism_ptr pmechanism, ck_object_handle hkey ); parameters hsession [in] session handle. pmechanism [in] mechanism to be used for verification. hkey [in] handle of the key to be used. description fc_verifyrecoverinit initializes a signature verification operation where the (digest) data can be recovered from the signature. a user must log into the token (to assume the nss user role) before calling fc_verifyrecoverinit. return value examples see also nsc_verifyrecoverinit ...
FC_VerifyUpdate
he data to be verified. uspartlen [in] length of data block in bytes. description fc_verifyupdate starts or continues a multi-part signature verification operation where the signature is an appendix to the data. one or more blocks may be part of the signature. the result for the entire message is returned by a call to fc_verifyfinal. a user must log into the token (to assume the nss user role) before calling fc_verifyupdate. return value examples see also fc_verifyfinal, nsc_verifyupdate ...
FC_WrapKey
o the location to receive the wrapped key or null. puswrappedkeylen [in, out] pointer to length of wrapped key buffer. description fc_wrapkey wraps (encrypts) a key. if pwrappedkey is null the length of the wrapped key is returned in puswrappedkeylen and fc_wrapkey may be called again with pwrappedkey set to retrieve the wrapped key. a user must log into the token (to assume the nss user role) before calling fc_wrapkey. return value examples see also nsc_wrapkey ...
NSC_InitToken
s nsc_inittoken() has the following parameters: slotid the id of the token's slot ppin the password of the security officer (so) ulpinlen the length in bytes of the so password plabel points to the label of the token, which must be padded with spaces to 32 bytes and not be null-terminated description nsc_inittoken() initializes a brand new token or re-initializes a token that was initialized before. specifically, nsc_inittoken() initializes or clears the key database, removes the password, and then marks all the user certs in the certificate database as non-user certs. (user certs are the 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 argume...
troubleshoot.html
troubleshooting nss and jss builds newsgroup: mozilla.dev.tech.crypto this page summarizes information on troubleshooting the nss and jss build and test systems, including known problems and configuration suggestions. if you have suggestions for this page, please post them to mozilla.dev.tech.crypto. building nss having /usr/ucb/bin in the path before /usr/ccs/bin breaks the build on 64-bit solaris. the solaris compiler needs to be workshop-5.0 or greater. the 64-bit builds don't support gcc. if the build fails early on the gmakein coreconf try updating your cvs tree with -p: cd mozilla cvs update -p building a 32-bit version on a 64-bit may fail with: /usr/include/features.h:324:26: fatal error: bits/predefs.h: no such file or directory in this case remember to set...
sslerr.html
sec_error_ocsp_unauthorized_request -8068 "the ocsp server has refused this request as unauthorized." sec_error_ocsp_unknown_response_status -8067 "the ocsp server returned an unrecognizable status." sec_error_ocsp_unknown_cert -8066 "the ocsp server has no status for the certificate." sec_error_ocsp_not_enabled -8065 "you must enable ocsp before performing this operation." sec_error_ocsp_no_default_responder -8064 "you must set the ocsp default responder before performing this operation." sec_error_ocsp_malformed_response -8063 "the response from the ocsp server was corrupted or improperly formed." sec_error_ocsp_unauthorized_response -8062 "the signer of the ocsp response is not authorized to...
ssltyp.html
re pointed to. otherwise, free both the structure pointed to and the secitem structure itself. returns the function returns one of these values: if successful, secsuccess. if unsuccessful, secfailure. use pr_geterror to retrieve the error code. description this function is similar to secitem_freeitem, except that it overwrites the structures to be freed with zeroes before it frees them. zeros and frees the memory associated with the structure to which the specified item points, when that structure is no longer used. when freeitem is not pr_false, also zeroes and frees the item structure itself. ...
NSS Tools sslstrength
= command. the second form attempts to connect to the named ssl host. the hostname argument must be present. however, the port number is an optional argument, and if not given, will default to the https port (443). restricting ciphers by default, sslstrength assumes that all the preferences are on, so it will use any preferences in your policy. the enabled ciphersuites will always be printed out before the connection is made. if you want to test out a particular cipher, there are two ways to affect which ciphers are available. firstly, you can set policy to be either domestic or export. this restricts the available ciphers to the same set used by communicator. in addition to this, the ciphers command can be used to further restrict the ciphers available. the argument to the ciphers command is a...
NSS Tools ssltap
by the client to the server and vice versa. the tool also displays the data to the shell window from which it was called. it can do this for plain http connections or any tcp protocol, as well as for ssl streams, as described here. the tool cannot and does not decrypt any encrypted message data. you use the tool to look at the plain text and binary data that are part of the handshake procedure, before the secure connection is established. syntax to run the ssl debugging tool, type this command in a command shell: ssltap [-vhfsxl] [-p port] hostname:port options the command does not require any options other than hostname:port, but you normally use them to control the connection interception and output. the options for the command are the following: -v print a version string f...
Tutorial: Embedding Rhino
he classpath. let's step through the body of main one line at time. entering a context the code context cx = context.enter(); creates and enters a context. a context stores information about the execution environment of a script. initializing standard objects the code scriptable scope = cx.initstandardobjects(); initializes the standard objects (object, function, etc.) this must be done before scripts can be executed. the null parameter tells initstandardobjects to create and return a scope object that we use in later calls. collecting the arguments this code is standard java and not specific to rhino. it just collects all the arguments and concatenates them together. string s = ""; for (int i=0; i < args.length; i++) { s += args[i]; } evaluating a script the code object res...
Rhino serialization
ved as markers upon serialization and resolved in the new scope upon deserialization. use the addexcludedname method of scriptableoutputstream to add new names. by default, scriptableoutputstream excludes all the names defined using context.initstandardobjects. if you are using rhino serialization in an environment where you always define, say, a constructor foo, you should add the following code before calling writeobject: out.addexcludedname("foo"); out.addexcludedname("foo.prototype"); this code will prevent foo and foo.prototype from being serialized and will cause references to foo or foo.prototype to be resolved to the objects in the new scope upon deserialization. exceptions will be thrown if foo or foo.prototype cannot be found the scopes used in either scriptableoutputstream or scripta...
Shumway
illa's github. several methods exist to allow inspector access to your swf file. once your flash content is loaded, you can see how shumway manages it in detail. several buttons are available at the bottom of the screen to enable or disable various shumway options. note: if your applet runs at an abnormal speed, try toggling "turbo" at the bottom of the inspector window. you may wish to do this before opening your swf file. limitations of shumway might be encountered through testing. there are two places where shumway bugs are tracked: github (via issues and pull requests) manages problems relating to shumway, itself. bugzilla is intended for problems with integrating shumway into firefox. end-users and less involved developers may report issues by hovering over "shumway" within flash ...
Creating JavaScript jstest reftests
f array sorting. you should not add tests of the following type: tests of the jit test of jit correctness belong in the jit-test suite, read more here. performance tests or stress tests tests of spidermonkey's comformance to the ecmascript standard a brief history: in 2017, spidermonkey started comsuming test262, a comprehensive tests suite for ecmascript implementations. before using test262, spidermonkey had a fair number of internal tests of conformance to ecmascript, and many of those tests remain in the js/src/non262 directory as regressions. test262 tests test262 is the implementation conformance test suite for the latest drafts of ecmascript language specification, as well as internationalization api specification and the json data interchange format. it is main...
Future directions
rward from now, the api will likely be semi-stable, but there is no guarantee. the public api is gradually moving from jsapi.h and jsfriendapi.h into header files in js/public. much more cleanup and organization is still required. practical coding bits experimental language features new language features (es6+) and apis often get added to spidermonkey while the spec is still being drafted, or before the feature has stabilized. this is good, because it helps the spec work. for these features: do not add vendor prefixes. see http://hsivonen.iki.fi/vendor-prefixes/ for an extended argument. disable the feature before the beta channel. nightly and aurora are the good channels for experimental work. nspr the plan is to make spidermonkey not depend on nspr. no fundamental blockers currently...
64-bit Compatibility
: const uintptr_t pointer_tagbits = 3 or by using a cast inside the macro. this sort of bug happens surprisingly often - see bug 501324, bug 512866 for example. amd64 pointers if mucking with pointers on amd64 (or em64-t/intel64), it is important to keep in mind an invariant that bits 63-48 must be sign-extended from bit 47. if you use these bits to squirrel away a payload, they must be adjusted before attempting to dereference the pointer. for more information and platform specific details on virtual address widths, see this article on wikipedia. builtins and calls when passing arguments to lirwriter::inscall(), there are four types: argsize_f - floating point value argsize_i - 32-bit integer argsize_q - 64-bit integer argsize_p - 32-bit integer on 32-bit platforms, 64-bit integer on 64-b...
Functions
think?) todo dslot instructions. jsop_{get,call}dslot (in flat closures only) todo gvar instructions. outside all functions, if a name definitely refers to a global for which we have seen a var, const, or function declaration, then we emit a js_defvar instruction in the script prelude and access the global using jsop_{get,set,call}gvar. this is fast if the global either doesn't exist before the script runs (the script creates it) or it's a non-configurable data property (which amounts to the same thing). otherwise the gvar instructions are as slow as name instructions. there are also combo instructions jsop_{inc,dec}gvar and jsop_gvar{inc,dec}. name instructions. in the worst case we emit jsop_{,set,call}name. these are totally general. they can still be optimized via the pr...
SpiderMonkey Internals
ring descriptors for efficient property name hashing, and as members of the root gc set for exact gc. standard library the methods for arrays, booleans, dates, functions, numbers, and strings are implemented using the js api. most are jsfastnatives. most string methods are customized to accept a primitive string as the this argument. (otherwise, spidermonkey converts primitive values to objects before invoking their methods, per ecma 262-3 §11.2.1.) error handling spidermonkey has two interdependent error-handling systems: javascript exceptions (which are not implemented with, or even compatible with, any kind of native c/c++ exception handling) and error reporting. in general, both functions inside spidermonkey and jsapi callback functions signal errors by calling js_reporterror or one of ...
INT_TO_JSVAL
t could be removed at any time. try to avoid using it. converts a specified integer value to a js integer value. please use js::int32value instead in spidermonkey 45 or later. syntax jsval int_to_jsval(int32_t i); name type description i any integer type c integer to convert to a jsval. description int_to_jsval converts a c integer, i, to a jsval. before spidermonkey 1.8.5, not all integers can be stored in a jsval; use int_fits_in_jsval to test. 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.") }} if i does not fit into a jsval (see int_fits_in_jsval), the behavior is undefined. to convert any number to a jsval, regardless of whether it fits in an int jsval, use j...
JS::CallArgs
largs is like so, using js::callargsfromvp: static bool functionreturningargctimesarg0(jscontext *cx, unsigned argc, js::value *vp) { js::callargs args = js::callargsfromvp(argc, vp); // guard against no arguments or a non-numeric arg0. if (args.length() == 0 || !args[0].isnumber()) { args.rval().setint32(0); return true; } // access to the callee must occur before accessing/setting // the return value. jsobject &callee = rec.callee(); // it's always fine to access thisv(). handlevalue thisv = rec.thisv(); args.rval().set(js::numbervalue(args.length() * args[0].tonumber())); // callee() and calleev() will now assert. return true; } see also mxr id search for js::callargs mxr id search for js::callargsfromvp js::call bug...
JS::DeflateStringToUTF8Buffer
, the function will encode characters from the string until the buffer is exhausted. does not write the null terminator. if dstlenp is provided, it will be updated to hold the number of bytes written to the buffer. if numcharsp is provided, it will be updated to hold the number of unicode characters written to the buffer. this can be less than the length of the string, if the buffer is exhausted before the string is fully encoded. examples char16_t uchars[] = { 0xd83e, 0xdd8a, 0 }; js::rootedstring str(cx, js_newucstringcopyn(cx, uchars, 2)); if (!str) return false; js::rooted<jsflatstring*> flatstr(cx, js_flattenstring(cx, str)); if (!flatstr) return false; size_t length = js::getdeflatedutf8stringlength(flatstr); char* buffer = static_cast<char*>(js_malloc(cx, length + 1)); if (!buffer)...
JS::PersistentRooted
ersistentrooted in such objects would introduce leaks. for these kinds of edges, heap<t> or tenuredheap<t> would be better types. it's up to the implementor of the type containing heap<t> or tenuredheap<t> members to make sure their referents get marked when the object itself is marked. js::persistentrooted<t> may be automatically coerced to a js::handle&lt;t&gt; and js::mutablehandle&lt;t&gt;. before spidermonkey 38, persistentrooted<t> itself cannot be a global variable, but from spidermonkey38, it can be declared as a global variable, and initialized later with init() method (bug 1107639). there are typedefs available for the main types: namespace js { typedef persistentrooted<jsfunction*> persistentrootedfunction; typedef persistentrooted<jsid> persistentrootedid; typedef persiste...
JS::SetOutOfMemoryCallback
name type description data void * data parameter passed to js::setoutofmemorycallback. added in spidermonkey 38 description unlike the error reporter, which is only called if the exception for an oom bubbles up and is not caught, the js::outofmemorycallback is called immediately at the oom site to allow the embedding to capture the current state of heap allocation before anything is freed. if the large-allocation-failure callback is called at all (not all allocation sites call the large-allocation-failure callback on failure), it is called before the out-of-memory callback; the out-of-memory callback is only called if the allocation still fails after the large-allocation-failure callback has returned. js::setoutofmemorycallback sets a callback function for it. ...
JSDeletePropertyOp
js_clearscope does not call this hook either. see also mxr id search for jsdeletepropertyop bug 858677 jsclass ...
JSEnumerateOp
jsenumerateop is the type of the jsclass.enumerate callback. syntax typedef bool (* jsenumerateop)(jscontext *cx, js::handleobject obj); name type description cx jscontext * pointer to the js context in which the enumeration is taking place. obj js::handleobject pointer to the object to be enumerated. description jsenumerateop is called just before an object is enumerated (via a for...in statement, an array comprehension, or a call to js_enumerate). it should define any remaining lazy properties that should be enumerable but are not yet defined in obj. this hook does not implement iteration: once the properties are defined, the javascript engine can enumerate them. jsclass hooks jsclass offers following hook: the jsclass.enumerate hook is...
JSErrorReport
rsion of the offending line of script. uctokenptr is a pointer into uclinebuf that identifies the precise location line of the problem within the offending unicode (original) version of the offending line. to use jserrorreport, your application must define a variable of type jserrorreport and allocate a buffer to hold the text that generated the error condition. set linebuf to point at the buffer before your application executes a script. for unicode scripts, define a second buffer that holds the unicode version of the text the generated the error. for application that do not use unicode, set uclinebuf and uctokenptr to null. macros name description jsreport_is_warning(flags) returns true if flags has jsreport_warning. jsreport_is_exception(flags) returns true...
JSObjectOps.lookupProperty
as a short-cut that bypasses id re-lookup. in any case, a non-null *propp result after a successful lookup must be dropped via jsobjectops.dropproperty. note: a successful return with non-null *propp means the implementation may have locked *objp and added a reference count associated with *propp, so callers should not risk deadlock by nesting or interleaving other lookups or any obj-bearing ops before dropping *propp. ...
JSPRINCIPALS_HOLD
. this argument must not be null. description jsprincipals_hold and jsprincipals_drop are used to manage memory for jsprincipals objects. principals are used by the spidermonkey security system. jsprincipals objects are not jsobjects. they are reference counted, not garbage collected. application code that stores a pointer to a jsprincipals object must call jsprincipals_hold(cx, principals) before storing it and jsprincipals_drop(cx, principals) when done with it. jsprincipals_hold(cx, principals) increments the reference count of principals by 1. jsprincipals_drop(cx, principals) decrements the reference count of principals by 1. if the reference count drops to 0, indicating that no one is using the object anymore, jsprincipals_drop also deallocates principals by calling its destroy metho...
JS_AddFinalizeCallback
ibed below, indicating the stage of finalize. iscompartment bool false if all compartments are being collected, true if a compartment is being collected. data void * data parameter specified in js_addfinalizecallback. added in spidermonkey 38 name description jsfinalize_group_start called when preparing to sweep a group of compartments, before anything has been swept. the collector will not yield to the mutator before calling the callback with jsfinalize_group_end status. jsfinalize_group_end called when preparing to sweep a group of compartments. weak references to unmarked things have been removed and things that are not swept incrementally have been finalized at this point. the collector may yield to the mutator after th...
JS_CStringsAreUTF8
8859-1, also known as iso-latin-1. that is, each byte is treated as a unicode character, and there is no way to pass in a string containing characters beyond u+00ff. however, spidermonkey can optionally interpret these strings as utf-8. there are two ways to enable this: at compile time, by building spidermonkey with js_c_strings_are_utf8 defined; or at run time, by calling js_setcstringsareutf8 before the first call to js_newruntime. enabling this option also causes js_getstringbytes and js_encodecharacters to produce utf-8 strings instead of latin-1. js_cstringsareutf8 returns js_true if the javascript engine is configured (either at compile time or at run time) to interpret char strings as utf-8. see also bug 805080 ...
JS_ClearContextThread
application that creates or uses a jscontext in one thread, then uses or destroys it in another thread, must use js_clearcontextthread and js_setcontextthread to transfer the jscontext safely from one thread to the other. the rules for using jscontexts in multiple threads are: each jscontext may only be used by one thread at a time. each request runs from start to finish on a single thread. before transferring a jscontext from thread a to thread b, thread a must call js_clearcontextthread. this is the last thing thread a does with the context. before thread b uses the jscontext, it must call js_setcontextthread. this is the first thing thread b does with the context, before beginning a request. so the usual code for using a jscontext on a thread other than the one where it was created l...
JS_ClearNewbornRoots
e type description cx jscontext * the context to clear. description the last gc thing of each type (object, string, double, external string types) created on a given context is kept alive until another thing of the same type is created, using a newborn root in the context. these newborn roots help native code protect newly-created gc-things from gc invocations activated before those things can be rooted using local or global roots. however, the newborn roots can also entrain great gobs of garbage, so the js_gc entry point clears them for the context on which gc is being forced. embeddings may need to do likewise for all contexts. see js_enterlocalrootscope for a better way to manage newborns in cases where native hooks (functions, getters, setters, etc.) create many gc...
JS_DefineProperties
nepropeties was not const. description js_defineproperties creates properties on a specified object, obj. ps is a pointer to the first element of an array of jspropertyspec structures. each array element defines a single property: its name, attributes, getter, and setter. the name field of the last array element must be null. js_defineproperties creates one property for each element in the array before the element with a null name field. each property is defined as though by calling js_defineproperties. the initial stored value of each property created is undefined. on success, js_defineproperties returns true, indicating it has created all properties listed in the array. otherwise it returns false. see also mxr id search for js_defineproperties js_defineconstdoubles js_defineelement js_define...
JS_DefineProperty
an currently replace jsprop_permanent properties, but such usage is deprecated. the javascript engine will call the getter or setter callback each time the property is read or written, whether from javascript code or via jsapi functions like js_getproperty and js_setproperty. (exception: if attrs contains the jsprop_readonly flag, the setter will never be called, as property assignment will fail before it gets that far. also note that certain jsapi functions, including js_lookupproperty, js_hasproperty, and property_attributes, can detect or examine a property without calling its getter.) if getter (or setter) is null, the new property will use the jsclass.getproperty (or jsclass.setproperty) callback from obj's class. if attrs contains the jsprop_getter (or jsprop_setter) flag, then getter (o...
JS_DeleteElement
ct, obj. if an object references an element belonging to a prototype, the element reference is removed from the object, but the prototype's element is not deleted. if deletion is successful, js_deleteelement returns true. otherwise it returns false. for javascript 1.2 and earlier, if failure occurs because you attempt to delete a permanent or read-only element, js_deleteelement reports the error before returning false. for javascript 1.3 and later, the attempt is silently ignored. to truncate an array, use js_setarraylength. to remove all elements and properties from an object, call js_clearscope. see also mxr id search for js_deleteelement bug 1113369 -- added result parameter ...
JS_EncodeCharacters
filled with encoded characters; or null. the caller is responsible for allocating and freeing this buffer. dstlenp size_t * in/out parameter. on entry, if dst is non-null, *dstlenp must be the length of the destination string in 16-bit units. on success, *dstlenp receives the length of the converted string, in bytes. on failure, *dstlenp receives the number of bytes written to dst before the error occurred. description js_encodecharacters copies the characters of a jschar array into a char array, converting the 16-bit values to 8-bit values. if spidermonkey was built with js_c_strings_are_utf8 defined or js_setcstringsareutf8 was called, the string is converted to utf-8. otherwise each character is simply truncated to 8 bits. if utf-8 is turned on, the length of the encode...
JS_ExecuteScript
to execute. rval js::mutablehandlevalue out parameter. on success, rval receives the value from the last executed expression statement processed in the script. description js_executescript executes a previously-compiled script, script. js::cloneandexecutescript handles a cross-compartment script. if the script is cross-compartment, it is cloned into the current compartment before executing. if the script executes successfully, rval receives the value from the last executed expression statement processed in the script, and js_executescript returns true. otherwise it returns false, and the value left in rval is unspecified. the jsapi user guide contains example code using compiled scripts. to execute a script that has not been compiled, use js::evaluate instead. see als...
JS_GetInstancePrivate
o the object's private data. otherwise it returns null. note that if obj is an instance of clasp, but there is no private data currently associated with the object, or the object cannot have private data, js_getinstanceprivate also returns null. if you pass a non-null argument vector, argv, to js_getinstanceprivate, and obj is not an instance of clasp, this function reports a class mismatch error before returning null. in this case, js_getinstanceprivate tests whether or not there is a function name associated with the argument vector, and if there is, reports the name in an error message using the js_reporterror function. see also mxr id search for js_getinstanceprivate jsclass_has_private jsval_to_private js_getprivate js_initclass js_instanceof js_reporterror js_setprivate bug 959787 -- adde...
JS_Init
es introduced in spidermonkey 31 initializes the js engine so that further operations can be performed. syntax #include "js/initialization.h" // previously "jsapi.h" bool js_init(void); description initialize spidermonkey, returning true only if initialization succeeded. once this method has succeeded, it is safe to call js_newruntime and other jsapi methods. this method must be called before any other jsapi method is used on any thread. once it has been used, it is safe to call any jsapi method, and it remains safe to do so until js_shutdown is correctly called. it is currently not possible to initialize spidermonkey multiple times (that is, calling js_init, jsapi methods, then js_shutdown in that order, then doing so again). this restriction may eventually be lifted. in the past j...
JS_LeaveCompartment
syntax void js_leavecompartment(jscontext *cx, jscompartment *oldcompartment); name type description cx jscontext * the context in which to leave the compartment. ...
JS_LeaveCrossCompartmentCall
ince 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. this article covers features introduced in spidermonkey 1.8.1 js_leavecrosscompartmentcall has been removed in bug 786068. use js_leavecompartment instead. leave a the compartment, returning to the compartment active before the corresponding js_entercrosscompartmentcall. syntax void js_leavecrosscompartmentcall(jscrosscompartmentcall *call); name type description call jscrosscompartmentcall * value returned by previous call to js_entercrosscompartmentcall. description every jscontext has a current compartment. any access to an object in a different compartment must be brackete...
JS_MakeStringImmutable
he substring's starting point and length, rather than as a separate copy of all the characters. this makes the substring operation, and regular expression matches, faster. in both cases, the javascript engine may change the fields of the jsstring. these changes are not atomic. therefore such strings must not be used by more than one thread at a time. applications must call js_makestringimmutable before sharing a jsstring among threads by storing it in a c/c++ variable, field, or array element that another thread can read. (when an application shares a string by storing it in a javascript object that another thread can read, the javascript engine automatically makes the string thread-safe.) after a successful call to js_makestringimmutable, subsequent calls to js_getstringcharsz on the same stri...
JS_NewContext
guide. the stackchunksize parameter does not control the javascript stack size. (the jsapi does not provide a way to adjust the stack depth limit.) passing a large number for stackchunksize is a mistake. in a debug build, large chunk sizes can degrade performance dramatically. the usual value of 8192 is recommended. the application must call js_destroycontext when it is done using the context. before a jsruntime may be destroyed, all the jscontexts associated with it must be destroyed. the new jscontext initially has no global object. the new jscontext is associated with the calling thread. no other thread may use it or destroy it. see also mxr id search for js_newcontext js_destroycontext js_contextiterator js_setcontextcallback ...
JS_NewExternalString
ontext * the context in which to create the new string. requires request. in a js_threadsafe build, the caller must be in a request on this jscontext. chars const char16_t * or const jschar * pointer to the first element of an array of char16_ts. this array is used as the character buffer of the jsstring to be created. the array must be populated with the desired character data before js_newexternalstring is called, and the array must remain in memory, with its contents unchanged, for as long as the javascript engine needs to hold on to it. (ultimately, the string will be garbage collected, and the javascript engine will call the string finalizer callback, allowing the application to free the array.) the array does not need to be zero-terminated. length size_t t...
JS_NewRuntime
llocated bytes after which garbage collection is run. maxnurserybytes uint32 nursery size in bytes. maxnurserybytes is rounded down to a multiple of chunk size. added in spidermonkey 38 parentruntime jsruntime * the topmost parent or nullptr . added in spidermonkey 31 description js_newruntime initializes the javascript runtime environment. call js_newruntime before making any other api calls except js_init. js_newruntime allocates memory for the jsruntime and initializes certain internal runtime structures. maxbytes specifies the number of allocated bytes after which garbage collection is run. if parentruntime is specified, the resulting runtime shares significant amounts of read-only state (the self-hosting and initial atoms compartments). it is recommende...
JS_PreventExtensions
description all javascript objects recognize the concept of extensibility: whether new properties may be added to the object. in some situations, it may be convenient to prohibit new properties. in javascript this may be accomplished using the object.preventextensions method. the similar jsapi method is js_preventextensions. the failure-mode information below is new as of spidermonkey 36. before then, js_preventextensions did not accept a succeeded argument; in those cases where *succeeded would be set to false, js_preventextensions would throw a typeerror and return false. unlike object.preventextensions, js_preventextensions doesn't necessarily throw a typeerror if the object couldn't be made non-extensible. there are instead two modes of failure: through internal error, and because...
JS_RemoveExternalStringFinalizer
nalizers table, returning its type code if found, -1 if not found. as with js_addexternalstringfinalizer, there is a threading restriction if you compile the engine js_threadsafe: this function may be called for a given finalizer pointer on only one thread; different threads may call to remove distinct finalizers safely. you must ensure that all strings with finalizer's type have been collected before calling this function. otherwise, string data will be leaked by the gc, for want of a finalizer to call. see also js_addexternalstringfinalizer bug 724810 ...
JS_SaveFrameChain
aves and restores frame chains. syntax bool js_saveframechain(jscontext *cx); void js_restoreframechain(jscontext *cx); name type description cx jscontext * the context to query. description these two functions are used to set aside cx's call stack while that stack is inactive. after a call to js_saveframechain, it looks as if there is no code running on cx. before calling js_restoreframechain, cx's call stack must be balanced and all nested calls to js_saveframechain must have had matching js_restoreframechain calls. js_saveframechain deals with cx not having any code running on it. see also mxr id search for js_saveframechain mxr id search for js_restoreframechain ...
JS_SetDestroyCompartmentCallback
)(jsfreeop *fop, jscompartment *compartment); name type description cx jsruntime * the runtime of the compartments. compartmentcallback jscompartment * the pointer to the compartment which is to be destroyed. description js_setdestroycompartmentcallback sets callback function which will be called when sweeping each compartment of the runtime, before deleting the compartment. see also mxr id search for js_setdestroycompartmentcallback mxr id search for jsdestroycompartmentcallback bug 737365 ...
JS_SetICUMemoryFunctions
n reallocfn, js_icufreefn freefn); type description allocfn js_icuallocfn an allocation function. reallocfn js_icureallocfn a reallocation function. freefn js_icufreefn a free function. description js_seticumemoryfunctions sets the allocator functions used by the icu internationalization library. it must be called before js_init. only use this function if you know what you are doing! mxr id search for js_seticumemoryfunctions. ...
JS_SetInterruptCallback
back using js_requestinterruptcallback. to schedule the gc and for other activities the engine internally triggers interrupt callbacks. the embedding should thus not rely on callbacks being triggered through the external api only. important note: additional callbacks can occur inside the callback handler if it re-enters the js engine. the embedding must ensure that the callback is disconnected before attempting such re-entry. js_setinterruptcallback sets a callback that can be called asynchronously. some common uses for an interrupt callback are: to run garbage collection periodically, by calling js_maybegc; to periodically take a break from script execution to update the ui (though note that mozilla does not do this, by design); to enforce application limits on the amount of time a sc...
JS_SetNativeStackQuota
keep higher-priority machinery running in the face of scripted stack exhaustion by something else. the stack quotas for each kind of code should be monotonically descending, and may be specified with this function. if 0 is passed for a given kind of code, it defaults to the value of the next-highest-priority kind. this function may only be called immediately after the runtime is initialized and before any code is executed and/or interrupts requested. see also mxr id search for js_setnativestackquota js_settrustedprincipals bug 516832 bug 732665 bug 723021 ...
JS_SetOperationCallback
back using js_triggeroperationcallback. to schedule the gc and for other activities the engine internally triggers operation callbacks. the embedding should thus not rely on callbacks being triggered through the external api only. important note: additional callbacks can occur inside the callback handler if it re-enters the js engine. the embedding must ensure that the callback is disconnected before attempting such re-entry. js_setoperationcallback sets a callback that can be called asynchronously. some common uses for an operation callback are: to run garbage collection periodically, by calling js_maybegc; to periodically take a break from script execution to update the ui (though note that mozilla does not do this, by design); to enforce application limits on the amount of time a sc...
JS_SetScriptStackQuota
nfigure. quota size_t the desired stack quota setting, in bytes. description set the quota on the number of bytes that stack-like data structures can use when the runtime compiles and executes scripts. these structures also consume heap space, so js_setthreadstacklimit does not bound their size. the default quota is 32mb which is quite generous. the function must be called before any script compilation or execution api calls, i.e. either immediately after js_newcontext or from the jscontext_new context callback. see also mxr id search for js_setscriptstackquota bug 644241 ...
JS_SetVersion
ntext * pointer to a js context from which to derive runtime information. version jsversion version of javascript to set context to. description js_setversion attempts to set the version of javascript to version for a specified executable script context, cx. the version comes from the jsversion enumerated type. js_setversion returns the js version in effect for the context before you changed it. see also mxr id search for js_setversion jsversion js_getversion js_versiontostring js_stringtoversion bug 880917 ...
JS_ShutDown
urces allocated by spidermonkey, not associated with any jsruntime, jscontext, or other structure. this method should be called after all other jsapi data has been properly cleaned up: every jsruntime created with js_newruntime must have been destroyed with js_destroyruntime, every jscontext created with js_newcontext must have been destroyed with js_destroycontext, and so on. calling this method before all other resources have been destroyed has undefined behavior. failure to call this method, at present, has no adverse effects other than leaking memory. this may not always be the case; it's recommended that all embedders call this method when all other jsapi operations have completed, to be future-proof. it is currently not possible to initialize spidermonkey multiple times (that is, calling j...
JS_SuspendRequest
se current request is to be suspended or resumed. savedepth jsrefcount (only in js_resumerequest) the valued returned by the matching js_suspendrequest call. description in js_threadsafe builds, when a multi-threaded application is in a request but needs to block or perform lengthy computation that can race safely with the garbage collector, it should call js_suspendrequest before the time-consuming operation and js_resumerequest after. for more information about thread safety and requests, see js_threadsafe. js_suspendrequest suspends any currently active requests associated with the context cx. this allows the runtime to perform garbage collection if needed and allows other threads to access objects that the calling thread had locked. the return value is the number of n...
JSAPI reference
if a variable is a root, then anything it points to will not be freed by the garbage collector. failure to root objects is a very common cause of mysterious crashes. class js::rooted<t> added in spidermonkey 17 class js::rootedobject added in spidermonkey 17 class js::rootedfunction added in spidermonkey 17 class js::rootedscript added in spide...
SpiderMonkey 1.8
ptstackquota limits the size of the javascript stack. two new functions, js_setgczeal and js_dumpheap, aim to help developers debug gc-related problems. these functions are only present in debug builds. js_setgczeal is especially helpful. when gc zeal is enabled, gc happens extremely frequently. this makes gc-related problems easier to reproduce, reveals gc problems that you may not have noticed before, and causes gc-safety bugs to surface much closer to their cause. js_dumpheap dumps parts of the gc heap and can help detect leaks. a new gc parameter, jsgc_stackpool_lifespan, controls how eagerly spidermonkey returns unused memory back to the system. the new function js_setextragcroots provides another way to protect values from garbage collection. there is a new set of apis for integrating ...
Using RAII classes in Mozilla
mporary. they cause no extra complexity for users of the class, but they do slightly complicate the implementation of the class. these macros are provided in guardobjects.h. in the common case, using these macros involves these three additions to a class: class moz_raii nsautoscriptblocker { public: explicit nsautoscriptblocker(jscontext *cx moz_guard_object_notifier_param) { // note: no ',' before macro moz_guard_object_notifier_init; nscontentutils::addscriptblocker(cx); } ~nsautoscriptblocker() { nscontentutils::removescriptblocker(); } private: moz_decl_use_guard_object_notifier }; moz_guard_object_notifier_param is added to the end of the constructor's parameter list. moz_guard_object_notifier_init is added as a statement in the constructor. moz_decl_use_guard_ob...
A Web PKI x509 certificate primer
t certificates included by default in mozilla products by following the mozilla ca certificate policy and applying for inclusion as per ca:how_to_apply. users may override the default root certificate settings using the certificate manager. some organizations make use of the set of cas included in mozilla's products. if you wish to do this, you should read the relevant part of the mozilla ca faq before doing so. running your own ca if you are going to have your own ca, we recommend building 3 certificates: a long term root cert, a medium term intermediate cert, and a short term end-entity cert. this type of hierarchy allows for a relatively simple long term root to be distributed to clients, and some flexibility on the intermediate cert so that you can change parameters based on best practice...
Signing Mozilla apps for Mac OS X
signing mozilla apps without the signing server firefox and thunderbird are built using mozilla's release automation infrastructure. on mac os x, part of this infrastructure is automatic signing of the ".app" folder using apple's codesign tool. ...
Gecko states
t_state_supports_autocompletion for editable areas that have any kind of autocompletion ext_state_defunct object no longer exists ext_state_selectable_text for text which is selectable, object must implement nsiaccessibletext ext_state_editable implements nsiaccessibleeditabletext ext_state_active this window is currently the active window ext_state_modal must do something with control before leaving it ext_state_multi_line edit control that can take multiple lines ext_state_horizontal uses horizontal layout ext_state_opaque indicates this object paints every pixel within its rectangular region ext_state_single_line this text object can only contain 1 line of text ext_state_transient ext_state_vertical especially used for sliders and scrollbars ext_state_stale object n...
History Service Design
cause fsyncs (to ensure data integrity) on the target filesystem. the temporary data (actually visits and pages) are synced to disk either on a timer and on bookmark's inserts. performance to ensure performance a bunch of statements, commonly used when adding or reading visit informations, are created at startup. these statements can be reused avoiding the overhead due to createstatement calls, before closing the connection these statements need to be finalized though, since not doing that would cause leaking. the internal syncing service takes care of initializing places, syncing data to disk and finalize statements, so usually that's not a problem. the same pre-compiled statements approach is used in other dependant services and in autocomplete. another step to improve performance is mainly...
Manipulating bookmarks using Places
the places bookmarks service, provided by the nsinavbookmarksservice interface, provides methods for creating, deleting, and manipulating bookmarks and bookmark folders. this article offers examples for how to perform common bookmark management tasks using the bookmarks service. initiating the bookmarks service as is the case with nearly all interfaces, before you can use the bookmarks service, you need to get access to it: var bmsvc = components.classes["@mozilla.org/browser/nav-bookmarks-service;1"] .getservice(components.interfaces.nsinavbookmarksservice); creating a bookmark folder creating a new bookmark folder is done using the nsinavbookmarksservice.createfolder() method. for example, to create a new folder in the bookmarks menu: var menufolder = b...
Querying Places
elves lazily, so opening a container actually corresponds to executing the given query. while a container is open, it will listen to the history and bookmarks systems' notifications and modify their contents to keep themselves up-to-date. for this reason, it is best to close a container as soon as you are done with it, since it will give better performance. if you close a container and re-open it before any history or bookmark change notifications come, the results will generally still be there and this operation will be fast. this example uses the places history service to display all the titles of the history pages. // queries parameters (e.g. domain name matching, text terms matching, time range...) // see : https://developer.mozilla.org/en/nsinavhistoryquery var query = placesutils.history...
Retrieving part of the bookmarks tree
y: var result = historyservice.executequery(query, options); get the results when you are querying for exactly one folder grouped by folder with no fancy query parameters such as keywords or date ranges (as in this example), the root of the result will be an nsinavhistorycontainerresultnode corresponding to your folder. if you have a complex query the root will be a nsinavhistoryqueryresultnode. before accessing the children of any result container, you must first open it, and then you can iterate the children. as long as the container is open, it will listen for notifications from the bookmarks system to keep itself up-to-date. when you're done, be sure to close the container to free up the resources. otherwise, it will continue to get observer notifications and update itself, slowing down the...
Using the Places history service
ete pages from a specific host, or pages from all hosts in a given domain. nsibrowserhistory.hidepage: hides a page so that it does not appear in the ui. many pages are not visible in normal history lists, such as redirects and sub-frame contents.this is not implemented in navhistory. nsibrowserhistory.markpageastyped: called by the url bar when the user types in a url. this can be and is calledbefore the page is actually added to history, since the page isn't added until it actually starts loading. the typed flag affects the url bar autocomplete. this will cause the transition type of the next visit of the url to be marked as "typed." nsinavhistoryservice.markpageasfollowedbookmark: called by the ui (implemented, but not yet called, see bug 409301) when the user selects a bookmark. this will...
Using the Places livemark service
the livemark service, offered by the nsilivemarkservice interface, is used to create, edit, and reload livemarks. you can also use it to check whether an item is a livemark. livemarks are bookmark folders that contain the most recent items from an rss feed. initiating the livemark service before using the livemark service, you need to obtain an instance: var livemarkservice = components.classes["@mozilla.org/browser/livemark-service;2"] .getservice(components.interfaces.nsilivemarkservice); creating a new livemark the nsilivemarkservice.createlivemark() method creates a new livemark. var newlvmkid = livemarkservice.createlivemark(parentfolderid, "livemark name", uri("http://example.com/"), ...
Using the Places tagging service
the tagging service, offered by the nsitaggingservice interface, provides methods to tag and untag a uri, to retrieve uris for a given tag, and to retrieve all tags for a uri. initiating the tagging service before using the tagging service, you need to obtain a reference to an instance of it: var taggingsvc = components.classes["@mozilla.org/browser/tagging-service;1"] .getservice(components.interfaces.nsitaggingservice); tagging a uri the nsitaggingservice.taguri() method tags a url with the given set of tags. current tags set for the url persist, and tags which are already set for the given url are ignored. taggingsvc.taguri(uri("http://example.com/"), ["tag 1"]); //first argument = uri //second argume...
places.sqlite Database Troubleshooting
y to) recover from a corrupt places.sqlite sometimes after a firefox/aurora/nightly upgrade, history disappears, but bookmarks are at their place. in the profile folder a places.sqlite-corrupt file has been created. in some cases, this procedure may allow you to recover the corrupt file along with all of its contents (history). close firefox and ensure it's done closing in your task manager. before you proceed, make a backup of the firefox profile folder, in any case. create a folder to use temporarily for this work, such as my_work_folder. copy places.sqlite-corrupt from the firefox profile folder to the work folder. download the latest precompiled binary sqlite command-line shell from: https://www.sqlite.org/download.html extract sqlite3 executable into the work folder. open a term...
Component Internals
s all global services. ns_shutdownxpcom returns and the application may exit normally. the unstoppable shutdown note that shutdown observation is unstoppable. in other words, the event you observe cannot be used to implement something like a "are you sure you want to quit?" dialog. rather, the shutdown event gives the component or embedding application a last chance to clean up any leftovers before they are released. in order to support something like an "are you sure you want to quit" dialog, the application needs to provide a higher-level event (e.g., startshutdown()) which allows for cancellation. note also that xpcom services may deny you access once you have received the shutdown notification. it is possible that xpcom will return an error if you access the nsiservicemanager at that p...
Setting up the Gecko SDK
be many different include paths), but it helps to organize the parts of the sdk meaningfully. the two top level header files are special. the file mozilla-config.h lists all of the defines used in the sdk. including this header file in your project ensures that the component you create uses the same defines as the gecko libraries themselves. note that mozilla-config.h may be need to be included before other includes in your component's source code. each module directory is divided into three 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 compone...
Detailed XPCOM hashtable guide
dom order (no sorting). nsthashtables can be allocated on the stack, as class members, or on the heap. entry pointers can and do change when items are added to or removed from the hashtable. do not keep long-lasting pointers to entries. because of this, nsthashtable is not inherently thread-safe. if you use a hashtable in a multi-thread environment, you must provide locking as appropriate. before using nsthashtable, see if nsbasehashtable and relatives will work for you. they are much easier to use, because you do not have to declare an entry class. if you are hashing a simple key type to a simple data type, they are generally a better choice. nsbasehashtable and friends: nsdatahashtable, nsinterfacehashtable, and nsclasshashtable these c++ templates provide a high-level interface for u...
Receiving startup notifications
cations, one needs to register with the "app-startup" category using nsicategorymanager; having done so, the component will receive these startup notifications, including: xpcom-startup sent when xpcom finishes starting up. most application features are not yet available at this point, but xpcom itself is. app-startup sent when the application has finished starting up. final-ui-startup sent just before the first application window is displayed. registering with the category manager to register with the category manager, simply call its nsicategorymanager.addcategoryentry() method: categorymanager->addcategoryentry(appstartup_category, "mycomponentname", "contract-id", pr_true, pr_true, ...
XPCOM Stream Guide
Mozilla › Tech › XPCOM › Guide › Streams
available immediately. (this is particularly true of streams that reach out over a network connection, like http and ftp channels.) stream listeners implement three methods. from the nsistreamlistener interface, the .ondataavailable(request, context, inputstream, offset, count) method gives you the input stream and the number of bytes available. the stream listener must read exactly count bytes before exiting. from the nsirequestobserver interface, the .onstartrequest(request, context) method tells you when the request begins, while the .onstoprequest(request, context) method tells you when the request ends. a request will have one .onstartrequest(request, context) call, followed by at least one .ondataavailable(...) call, followed by one .onstoprequest(request, context) call. the context arg...
Components.classes
add-on component with a given contractid will be present on one machine but not have been installed on another machine. if the given element in the components.classes object is not registered on the machine then trying to access it will generate a javascript warning in strict mode and the value returned will be the javascript value undefined. you should use the in operator to test for the element before trying to access it: if (!("@some/bogus/class;1" in components.classes)) // do something... the properties of the components.classes object can be enumerated using a for...in loop. usage in order to retrieve the object for a given contractid, you can query the components.classes array as follows: var clazz0 = components.classes["@mozilla.org/messenger;1"]; clazz0 is the class object for...
Components.utils.forceGC
) xpcom objects hanging off javascript objects though. in many cases a javascript application will have internal knowledge of javascript objects referencing large (trees of) xpcom objects and know when they are no longer reachable. in this case it can be important to be able to force a garbage collection cycle from javascript. another instance where it can be useful to force garbage collection is before cleaning out dead reference from a hash of weak javascript references. users should note that garbage collection is a very expensive operation and should only be forced when it is known to be absolutely necessary. note: nsidomwindowutils.garbagecollect() offers similar functionality but will trigger the cycle collector in addition to the garbage collector in the javascript engine. this will mak...
HOWTO
solution 1. ...
Profiling XPCShell
ime spend; the total time; the time spend in the function itself is given (that is the total time excluding the time spend in functions called from this function). notes you need a trunk build from after 2007-05-28. using an earlier build will cause the profiler to hang the more adventurous can use the nsixpctoolsprofiler.idl interface directly, but be aware that you must start the profiler before loading the files you want to profile (creating an instance of a component loads the file!) ...
XPCShell Reference
(setting this option disables the "interactive" mode) -f this option specifies a script file to execute. xpcshell terminates upon script completion. you can specify multiple js files to execute by using multiple -f arguments, and the scripts will be executed in the order encountered. furthermore, xpcshell looks for xpcshell.js in the current directory. if that file is found, it is executed before any other js files specified. -g this option specifies which gecko runtime environment directory (gredir) to use for xpcom. -i this option turns on the "interactive" mode -s this option toggles the javascript strict option on and off. by default it is off. -v version this allows you to specify a specific version of js to use, and should be set to an integral value specified by the j...
NS_InitXPCOM2
cific directories and files (e.g., the user profile, the component registry, etc.). this parameter may be nsnull. return values the ns_initxpcom2 function returns ns_ok if successful. otherwise, it returns an error code. some of the possible errors are documented below: ns_error_not_initialized indicates that static globals were not yet initialized, which may happen if this method is called before xpcom's static initialization code executes. this error may also occur if xpcom is being initialized after ns_shutdownxpcom has been called. remarks you must call ns_initxpcom2 (or ns_initxpcom3) before proceeding to use xpcom in a process. the one exception is that you may call ns_newlocalfile or ns_newnativelocalfile to create a nsifile needed for the abindirectory parameter to ns_initxpcom2...
NS_InitXPCOM3
static modules to be registered, if present. astaticmodulecount [in] the number of elements in astaticmodules. return values the ns_initxpcom3 function returns ns_ok if successful. otherwise, it returns an error code. some of the possible errors are documented below: ns_error_not_initialized indicates that static globals were not yet initialized, which may happen if this method is called before xpcom's static initialization code executes. this error may also occur if xpcom is being initialized after ns_shutdownxpcom has been called. remarks you must call ns_initxpcom3 (or ns_initxpcom2) before proceeding to use xpcom in a process. the one exception is that you may call ns_newlocalfile or ns_newnativelocalfile to create a nsifile needed for the abindirectory parameter to ns_initxpcom3...
IAccessibleEditableText
omplements that interface with the additional capability of clipboard operations. note that even a read only text object can support the copy capability so this interface is not limited to editable objects. the substrings used with this interface are specified as follows: if startoffset is less than endoffset, the substring starts with the character at startoffset and ends with the character just before endoffset. if endoffset is lower than startoffset, the result is the same as a call with the two arguments exchanged. the whole text can be defined by passing the indices zero and iaccessibletext.ncharacters(). if both indices have the same value, an empty string is defined. refer to the @ref _specialoffsets "special offsets for use in the iaccessibletext and iaccessibleeditabletext methods" for ...
imgICache
e ); parameters chrome if true, evict only chrome images. if false, evict everything except chrome images. findentryproperties() find properties used to get properties such as 'type' and 'content-disposition' 'type' is a nsisupportscstring containing the images' mime type such as 'image/png' 'content-disposition' will be a nsisupportscstring containing the header if you call this before any data has been loaded from a uri, it will succeed, but come back empty. nsiproperties findentryproperties( in nsiuri uri ); parameters uri the uri to look up. return value null if the url was not found in the cache. removeentry() evict images from the cache. void removeentry( in nsiuri uri ); parameters uri the uri to remove. exceptions thrown ns_o...
imgIDecoderObserver
discardable. moreover, they can be interleaved in various ways. in general, any presumed ordering between load and decode notifications should not be relied upon. decode notifications may or may not be synchronous, depending on the situation. if imgidecoder::flag_sync_decode is passed to a function that triggers a decode, all notifications that can be generated from the currently loaded data fire before the call returns. if flag_sync_decode is not passed, all, some, or none of the notifications may fire before the call returns. method overview void ondataavailable(in imgirequest arequest, in boolean acurrentframe, [const] in nsintrect arect); native code only! void ondiscard(in imgirequest arequest); void onimageisanimated(in imgirequest arequest); void onst...
imgIEncoder
ys included in the count. plays=# -- default: "0" number of times to play the animation sequence. "0" will repeat forever. the following options can be used for each frame, with addimageframe(): transparency=[yes|no|none] -- default: "yes" overrides default from input format. "no" and "none" are equivalent. delay=# -- default: "500" number of milliseconds to display the frame, before moving to the next frame. dispose=[none|background|previous] -- default: "none" what to do with the image's canvas before rendering the next frame. see apng spec. blend=[source|over] -- default: "source" how to render the new frame on the canvas. see apng spec. xoffset=# -- default: "0" yoffset=# -- default: "0" where to draw the frame, relative to the canvas. jpeg: ----- qua...
inIDOMUtils
uded or property aliases included. see constants. acount optional count aprops properties getcssstylerules() returns an array of the css style rules on the specified element. nsisupportsarray getcssstylerules( in nsidomelement aelement, in domstring apseudo optional ); parameters aelement a dom element to retrieve the style rules of. apseudo optional a pseudo element, such as before. return value an nsisupportsarray containing all the style rules that currently apply to the element, in ascending order of weight. getparentfornode() returns the parent of the specified node. nsidomnode getparentfornode( in nsidomnode anode, in boolean ashowinganonymouscontent ); parameters anode the node to return the parent of. ashowinganonymouscontent whether you are interes...
mozIColorAnalyzer
nce is given to colors that are more interesting. it avoids the background color if it can be discerned and ignores sufficiently transparent colors. this is intended to be used on favicon images. larger images take longer to process, especially those with a larger number of unique colors. if imageuri points to an image that has more than 128^2 pixels, this method will fail for performance reasons before analyzing it. void findrepresentativecolor( in nsiuri imageuri, in mozirepresentativecolorcallback callback ); parameters imageuri a uri pointing to the image - ideally a data: uri, but any scheme that will load when setting the src attribute of a dom img element should work. callback function to call when the representative color is found or an error occurs. rem...
mozISpellCheckingEngine
o dictionary is selected. note: setting this value to a value that doesn't match an existing dictionary throws a ns_error_file_not_found exception. when this attribute's value is changed, a "spellcheck-dictionary-update" notification is sent. if the dictionary was set to "no dictionary" (that is, by specifying an empty string), the observer may select another dictionary before returning. language wstring the language this spell checker is using when checking. this is the language of dictionary. read only. when this changes, the spell checker sends a "spellcheck-dictionary-update" notification. name wstring the name of the engine. not currently used. read only. persona...
mozIStorageStatementParams
for (let param in statement.params) statement.params[param] = valuestobind[param]; ...
mozITXTToHTMLConv
t the beginning of the line to indicate cite levels. unsigned long citeleveltxt( in wstring line, out unsigned long loglinestart ); parameters line the original line of text, which may begin with one or more cite characters such as ">". loglinestart on output, this parameter is set to indicate the offset into the string of the first non-cite character. you must set this value to zero before calling this method. return value the cite level of the quote; that is, the number of text quote characters found at the beginning of the string. findurlinplaintext() returns the start and end offsets of the first url found in a substring. void findurlinplaintext( in wstring text, in long alength, in long apos, out long astartpos, out long aendpos ); parameters text the stri...
nsIAbCard
tself. if cached by the caller and supplied to this function, then performance will be improved over many calls. return value a string containing the generated name. generatephoneticname() generate a phonetic name from the card, using the firstname and lastname values. astring generatephoneticname(in boolean alastnamefirst) parameters alastnamefirst set to true to put the last name before the first. return value a string containing the generated phonetic name. ...
nsIAccessibleStates
any kind of auto completion. ext_state_defunct 0x00000002 object no longer exists. ext_state_selectable_text 0x00000004 for text which is selectable, object must implement nsiaccessibletext. ext_state_editable 0x00000008 implements nsiaccessibleeditabletext. ext_state_active 0x00000010 this window is currently the active window. ext_state_modal 0x00000020 must do something with control before leaving it. ext_state_multi_line 0x00000040 edit control that can take multiple lines. ext_state_horizontal 0x00000080 uses horizontal layout. ext_state_opaque 0x00000100 indicates this object paints every pixel within its rectangular region. ext_state_single_line 0x00000200 this text object can only contain 1 line of text. ext_state_transient 0x00000400 ext_state_vertical 0x0000080...
nsIAppShell
preventing event starvation. void favorperformancehint( in boolean favorperfoverstarvation, in unsigned long starvationdelay ); parameters favorperfoverstarvation true to favor event performance over event starvation, false to favor event starvation over event performance. starvationdelay is only used when favorperfoverstarvation is pr_false. it is the amount of time in milliseconds to wait before the pr_false actually takes effect. getnativeevent() obsolete since gecko 1.9 (firefox 3) after event dispatch execute app specific code. void getnativeevent( in prboolref arealevent, in voidptrref aevent ); parameters arealevent event is real or a null placeholder (macintosh). aevent void pointer to native event structure. listentoeventqueue() o...
nsIAuthPromptCallback
netwerk/base/public/nsiauthpromptcallback.idlscriptable interface for callback methods for the asynchronous nsiauthprompt2 method. 1.0 66 introduced gecko 1.9 inherits from: nsisupports last changed in gecko 1.9 (firefox 3) callers must call exactly one method if nsiauthprompt2.asyncpromptauth() returns successfully. they must not call any method on this interface before nsiauthprompt2.asyncpromptauth() returns. method overview void onauthavailable(in nsisupports acontext, in nsiauthinformation aauthinfo); void onauthcancelled(in nsisupports acontext, in boolean usercancel); methods onauthavailable() authentication information is available. note: any exceptions thrown from this method should be ignored. void onauthavailable( in nsisuppor...
nsIBlocklistPrompt
1.0 66 introduced gecko 2.0 inherits from: nsisupports last changed in gecko 2.0 (firefox 4 / thunderbird 3.3 / seamonkey 2.1) method overview void prompt([array, size_is(acount)] in nsivariant aaddons, [optional] in pruint32 acount); methods prompt() prompt the user about newly blocked addons. ...
nsIBrowserHistory
(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.markpageastyped() instead. this method designates the url as having been explicitly typed in by the user, so it can be used as an autocomplete result. it is called by the url bar when the user types in a url. this can be and is called before the page is actually added to history, since the page isn't added until it actually starts loading. the typed flag affects the url bar autocomplete. this will cause the transition type of the next visit of the url to be marked as "typed." void markpageastyped( in nsiuri auri ); parameters auri the page that is to be marked as typed by the user. registeropenpage() obsol...
nsIChannelEventSink
ace to gain control over various channel events, such as redirects. 1.0 66 introduced gecko 1.8 inherits from: nsisupports last changed in gecko 2.0 (firefox 4 / thunderbird 3.3 / seamonkey 2.1) channels will try to get this interface from a channel's notificationcallbacks or, if not available there, from the loadgroup's notificationcallbacks. these methods are called before onstartrequest. note: prior to gecko 2.0, redirect handling was synchronous, using the onchannelredirect() method. starting in gecko 2.0, that method no longer exists, and instead the asynconchannelredirect() method is called; this uses a callback to handle redirects asynchronously. method overview void asynconchannelredirect(in nsichannel oldchannel, in nsichannel newchannel, in unsi...
nsIConsoleService
ners 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(); parameters none. note: console listeners expect you to log an empty string message before calling reset, so they too can clear their message buffers. (this also works before gecko 19.) unregisterlistener() deregisters a listener. void unregisterlistener( in nsiconsolelistener listener ); parameters listener the nsiconsolelistener to remove. examples retrieving the message array to retrieve the message array in gecko prior to version 19: function getconsolemessagearray(...
nsIContentPrefCallback2
letion() called when the method finishes. this will be called exactly once for each method invocation, and afterward no other callback methods will be called. void handlecompletion( in unsigned short reason ); parameters reason one of the complete_* values indicating the manner in which the method completed. handleerror() called when an error occurs. this may be called multiple times before handlecompletion is called. void handleerror( in nsresult error ); parameters error a number in components.results describing the error. handleresult() for the retrieval methods, this is called once for each retrieved preference. it is not called for other methods. void handleresult( in nsicontentpref pref ); parameters pref the retrieved preference. see also nsiconten...
nsIContentPrefService2
ck); void setglobal(in astring name, in nsivariant value, in nsiloadcontext context, [optional] in nsicontentprefcallback2 callback); methods addobserverforname() registers an observer that will be notified whenever a preference with the given name is set() or removed. when a set() or remove method is called, observers are notified after the set() or removal completes but before method's callback is called. the service holds a strong reference to the observer, so the observer must be removed later to avoid leaking it. void addobserverforname( in astring name, in nsicontentprefobserver observer ); parameters name the name of the preferences to observe. pass null to observe all preference changes regardless of name. observer the observer. ...
nsIContentViewer
ntry that the content viewer was stored in. the entry must have the docshells for all of the child documents stored in its child shell list. pagehide() void pagehide( in boolean isunload ); parameters isunload missing description exceptions thrown missing exception missing description permitunload() determins whether or not the document wants to prevent unloading by firing beforeunload on the document, and if it does, prompts the user. the result is returned. boolean permitunload( in boolean acallercloseswindow optional ); parameters acallercloseswindow optional indicates that the current caller will close() the window. if the method returns true, all subsequent calls will be ignored. return value true if the document will allow unloading; otherwise false. re...
nsIConverterOutputStream
e, use: var converteroutputstream = components.classes["@mozilla.org/intl/converter-output-stream;1"] .createinstance(components.interfaces.nsiconverteroutputstream); method overview void init(in nsioutputstream aoutstream, in string acharset, in unsigned long abuffersize, in prunichar areplacementcharacter); methods init() initialize this stream. must be called before any other method on this interface, or you will crash. the output stream passed to this method must not be null, or you will crash. void init( in nsioutputstream aoutstream, in string acharset, in unsigned long abuffersize, in prunichar areplacementcharacter ); parameters aoutstream the underlying output stream to which the converted strings will be written. acharset the character set t...
nsICryptoHMAC
ary data. return value a hash of the data that was read by this object. this can be either binary data or base 64 encoded. exceptions thrown ns_error_not_initialized if init() has not been called. init() initialize the hashing object. this method may be called multiple times with different algorithm types. warning: this approach is not fips compliant. note: this method must be called before any other method on this interface is called. void init( in unsigned long aalgorithm, in nsikeyobject akeyobject ); parameters aalgorithm the algorithm type to be used. this value must be one of the above valid algorithm types. akeyobject object holding a key. to create the key object use for instance: var keyobject = components.classes["@mozilla.org/security/keyobjectfact...
nsIDBChangeListener
red value of astatus is provided, so that any changes may be noted. void onhdrpropertychanged(in nsimsgdbhdr ahdrtochange, in prbool aprechange, inout pruint32 astatus, in nsidbchangelistener ainstigator); parameters ahdrtochange the nsimsgdbhdr of the message that is changing. aprechange true on first call before change, false on second call after change. astatus the storage location provided by calling routine for status. ainstigator the caller who added the header. this can be used to filter out events that you yourself started. ainstigator may also be null. onevent() generic notification for extensibility. common events should be documented here so we have a hope of keeping the documentation up ...
nsIDOMGeoPositionOptions
s/geolocation/nsidomgeopositionoptions.idlscriptable please add a summary to this article. last changed in gecko 1.9.1 (firefox 3.5 / thunderbird 3.0 / seamonkey 2.0) inherits from: nsisupports attributes attribute type description enablehighaccuracy boolean if true, high accuracy mode is used. timeout unsigned long maximum time in milliseconds before giving up on an attempt to retrieve location information. ...
nsIDOMHTMLSourceElement
ue must be a valid url. this attribute must be present. note that dynamically manipulating this value after the page has loaded has no effect on the containing element; instead, change the src attribute of that element (audio or video) instead. type domstring the type attribute gives the type of the media resource, to help the user agent determine if it can play this media resource before fetching it. if specified, its value must be a valid mime type. the codecs parameter may be specified and might be necessary to specify exactly how the resource is encoded. media unimplemented domstring the media attribute gives the intended media type of the media resource, to help the user agent determine if this media resource is useful to the user before fetching it. its value ...
nsIDebug
assertion. aline line number of assertion. break() requests the software break into a debugger. if no debugger is running then this usually results in a program crash. however, on windows a dialog is first presented giving the user the option of aborting, breaking, or ignoring the request. the dialog can be suppressed by use of the windbgdlg registry key. this allows the debugger to be attached before the software break. void break( in string afile, in long aline ); parameters afile file containing break request. aline line number of break request. warning() shows a warning. void warning( in string astr, in string afile, in long aline ); parameters astr warning message. afile file containing warning. aline line number of warning. see also nsidebug2 ...
nsIDialogParamBlock
value the string at the given index, or the empty string if no string has previously been set at that index. setint() void setint( in print32 inindex, in print32 inint ); parameters inindex the index of the integer to set. must be in the range 0..7. inint the integer to set at the given index. setnumberstrings() set the maximum number of strings to pass. default is 16. use before setting any string (if you want to change it from the default). this method can only be called once. void setnumberstrings( in print32 innumstrings ); parameters innumstrings the new maximum number of strings to pass. setstring() void setstring( in print32 inindex, in wstring instring ); parameters inindex the index of the string to set. must be in the range 0..15 unles...
nsIDirectoryService
plements this interface to provide support for a variety of well-known file and directory locations. inherits from: nsisupports last changed in gecko 1.7 method overview void init(); void registerprovider(in nsidirectoryserviceprovider prov); void unregisterprovider(in nsidirectoryserviceprovider prov); init() initializes the nsidirectoryservice instance. this method must be called before an nsidirectoryservice instance can be used. in the case of the xpcom directory service, this method is called as part of xpcom initialization. must not be called by external code; called internally by xpcom initialization. void init(); parameters none. registerprovider() register a provider with the service. the directory service will keep a strong reference to the nsidirectoryserviceprovider...
nsIDynamicContainer
ry. containers should follow these when possible, for example, whether to expand queries, etc. implementations should use this when possible if adding query and folder nodes to the container. do not modify this value. oncontainerremoving() this method is called when the given container is about to be deleted from the bookmarks table, so that the service can do any necessary cleanup. it is called before the container is deleted, so that the service can still reference it. void oncontainerremoving( in long long aitemid ); parameters aitemid the item-id of the container item. see also places nsinavhistorycontainerresultnode nsinavhistoryqueryoptions nsinavbookmarksservice.createdynamiccontainer() ...
nsIEditorDocShell
ieditor gets or sets the editor for the content document. haseditingsession boolean this docshell has an editing session. read only. methods makeeditable() make this docshell editable, setting a flag that causes an editor to get created, either immediately, or after a url has been loaded. void makeeditable( in boolean inwaitforuriload ); parameters inwaitforuriload true to wait for a uri before creating the editor. ...
nsIEditorSpellCheck
void savedefaultdictionary(); parameters none. setcurrentdictionary() selects the main dictionary to use. void setcurrentdictionary( in astring dictionary ); parameters dictionary the name of the dictionary to use. typically, this is an iso language code such as "en-us". setfilter() used to filter the content (for example, to skip blockquotes in email from spell checking). call this before calling initspellchecker(); calling it after initialization will have no effect. void setfilter( in nsitextservicesfilter filter ); parameters filter an nsitextservicesfilter describing the filter to apply. this filter lets you avoid spell checking specific parts of the document. uninitspellchecker() call this to release the spell checking object. it will also save the current select...
nsIEffectiveTLDService
ed aadditionalparts value. ns_error_host_is_ip_address this exception is thrown if ahost is a numeric ipv4 or ipv6 address. remarks note: prior to gecko 2.0 (firefox 4 / thunderbird 3.3 / seamonkey 2.1), this method worked if you passed host strings starting with a period ("."). that is no longer the case, since these are not valid host names. you should strip leading periods off host names before passing them to this method. getpublicsuffix() returns the public suffix of a uri. a public suffix is the highest-level domain under which individual domains may be registered; it may therefore contain one or more dots. for example, the public suffix for www.bbc.co.uk is co.uk. likewise, the public suffix for developer.mozilla.org is org. acstring getpublicsuffix( in nsiuri auri ); parame...
nsIExternalHelperAppService
boolean applydecodingforextension( in autf8string aextension, in acstring aencodingtype ); parameters aextension the filename extension to check. aencodingtype the encoding type to check. return value true if data from urls with the specified extension and encoding should be decoded prior to saving the file or delivering it t...
nsIFaviconDataCallback
or called on success only. check the method documentation to ensure that. the caller will receive the most information we can gather on the icon, but it's not guaranteed that all of them will be set. for some method we could not know the favicon's data (it could just be too expensive to get it, or the method does not require we actually have any data). it's up to the caller to check adatalen > 0 before using any data-related information like mime-type or data itself. void oncomplete( in nsiuri auri, in unsigned long adatalen, [const,array,size_is(adatalen)] in octet adata, in autf8string amimetype ); parameters auri receives the "favicon uri" (not the "favicon link uri") associated to the requested page. this can be null if there is no associated favicon uri, or the cal...
nsIFeedProgressListener
most likely that most or all of the feed-level metadata has been processed and is available in the received nsifeedresult object. note: if the feed type is one of the entry or item-only types, this event will never be called. void handlefeedatfirstentry( in nsifeedresult result ); parameters result an nsifeedresult describing the feed at the point at which the first entry is found, but before processing it. handlestartfeed() called as soon as a reasonable start to a feed is detected; this lets your code know that the feed does appear to be an actual feed rather than some other sort of document. void handlestartfeed( in nsifeedresult result ); parameters result an nsifeedresult describing the current state of the feed at the moment parsing begins. reporterror() called by...
nsIFeedResult
cko 1.8 (firefox 1.5 / thunderbird 1.5 / seamonkey 1.0) method overview void registerextensionprefix(in astring anamespace, in astring aprefix); attributes attribute type description bozo boolean the feed processor sets the bozo bit when a feed triggers a fatal error during xml parsing. there may still be feed metadata and entries that were parsed before the error occurred. doc nsifeedcontainer the parsed feed or entry. null if a non-feed was processed. headers nsiproperties the http response headers that accompanied the feed. stylesheet nsiuri an xslt stylesheet available to transform the source of the feed. some feeds include this information in a processing instruction. it's generally intended for u...
nsIFeedResultListener
6 introduced gecko 1.8 inherits from: nsisupports last changed in gecko 1.8 (firefox 1.5 / thunderbird 1.5 / seamonkey 1.0) method overview void handleresult(in nsifeedresult result); methods handleresult() called when feed processing is complete. even if an error occurred during processing, there may be valid data available for feed-level data or entries processed before the error occurred. if you don't care about doing progress display or the like, this is all you need to implement in order to receive the parsed feed. void handleresult( in nsifeedresult result ); parameters result an nsifeedresult describing the parsed feed. see also nsifeedprogresslistener nsisupports interwiki link ...
nsIFile
nk. otherwise it returns false. iswritable() this method tests whether or not this nsifile corresponds to a file or directory that may be modified by the user. as of gecko 9, files on read only shares will return false. files that are exclusively opened on win32 will return true if they are normally writable, and files that don't have write permissions will return false. for specific handling before gecko 9 (firefox 9.0 / thunderbird 9.0 / seamonkey 2.6), please see bug 682571. boolean iswritable(); parameters none. return value true if the file or directory may be modified by the user. otherwise it returns false. moveto() this method moves this file to a new location. note: if this method succeeds, this instance will be updated to point to the new file. if the current file path co...
nsIFileStreams
sifilestreams.idlscriptable please add a summary to this article. last changed in gecko 1.9 (firefox 3) inherits from: nsisupports method overview void init(in nsifile file, in long ioflags, in long perm, in long behaviorflags); constants constants value description delete_on_close 1<<1 if this is set, the file will be deleted by the time the stream is closed. it may be removed before the stream is closed if it is possible to delete it and still read from it. if open_on_read is defined, and the file was recreated after the first delete, the file will be deleted again when it is closed again. close_on_eof 1<<2 if this is set, the file will close automatically when the end of the file is reached. reopen_on_rewind 1<<3 if this is set, the file will be reopened whenever seek(0...
nsIFileURL
ponding to a url. the url scheme need not be file:, since other local protocols may map urls to files (e.g., resource:). inherits from: nsisupports last changed in gecko 6.0 (firefox 6.0 / thunderbird 6.0 / seamonkey 2.3) attributes attribute type description file nsifile get/set nsifile corresponding to this url. the getter returns a reference to an immutable object. callers must clone before attempting to modify the returned nsifile object. note: this constraint might not be enforced at runtime, so beware! the setter clones the nsifile object (allowing the caller to safely modify the nsifile object after setting it on this interface). ...
nsIFrameMessageManager
tional in boolean listenwhenclosed ); parameters amessage the name of the message for which to add a listener. alistener an object implementing nsiframemessagelistener whose receivemessage method will be called when the message is received. listenwhenclosed default is false. set to oo if you want to receive messages during the short period after a frame has been removed from the dom and before its frame script has finished unloading. this parameter only has an effect for frame message managers in the main process. an alternative method to listen for death of frame script is to use message-manager-disconnect observer: observer notifications :: message manager. removemessagelistener() removes a message listener previously added by calling addmessagelistener(). void removemessagelist...
nsIGeolocationProvider
ete since gecko 1.9.2 (firefox 3.6 / thunderbird 3.1 / fennec 1.0) reports whether or not the device is ready and has a position. boolean isready(); parameters none. return value true if the device is ready and has a position available to return; otherwise false. shutdown() shuts down the location device. void shutdown(); parameters none. startup() start up the provider. this is called before any other method and may be called multiple times. void startup(); parameters none. watch() attaches a callback listener to be notified when a location change is observed. void watch( in nsigeolocationupdate callback ); parameters callback an nsigeolocationupdate to be notified when position changes. your location provider should call this routine whenever new position data is available. se...
nsIHTMLEditor
which may have child nodes, at the selection used primarily to insert a new element for various insert element dialogs, but it enforces the html 4.0 dtd "cancontain" rules, so it should be useful for other elements. void insertelementatselection( in nsidomelement aelement, in boolean adeleteselection ); parameters aelement the element to insert. adeleteselection delete the selection before inserting if adeleteselection is pr_false, then the element is inserted after the end of the selection for all element except named anchors, which insert before the selection. insertfromdrop() looks for a dragsession and inserts the relevant data in response to a drop. void insertfromdrop( in nsidomevent aevent ); parameters aevent inserthtml() insert some html source at the curr...
nsIINIParserWriter
yinterface(components.interfaces.nsiiniparserwriter); here, somelocalfile is an nsifile based object, such as an nsilocalfile. this indicates the file into which the ini data will be written. once the writer object is created, you can use the setstring() method to set the value of a property within a given section; the section is created if it hasn't been yet. the sections are built in memory before the text of the ini file is generated, so you can add properties to the file in any order, regardless of section. when you're done and ready to write the ini file to disk, call the writefile() method. method overview void setstring(in autf8string asection, in autf8string akey, in autf8string avalue); void writefile([optional] in nsifile ainifile, [optional] in unsigned long a...
nsIIdleService
ng in gecko 1.9.2, there is a once a day notification sent out if the user remains idle for an extended period: 'idle-daily'. the data parameter for the notification contains the current user idle time. void addidleobserver( in nsiobserver observer, in unsigned long time ); parameters observer the nsiobserver to be notified. time the amount of time in seconds the user should be idle before the observer should be notified. removeidleobserver() remove an observer registered with addidleobserver(). note: removing an observer will remove it once, for the idle time you specify. if you have added an observer multiple times, you will need to remove it just as many times. void removeidleobserver( in nsiobserver observer, in unsigned long time ); parameters observer the nsiob...
nsIInputStream
sure, in unsigned long acount); native code only! methods available() determine number of bytes available in the stream. in addition to the number of bytes available in the stream, this method also informs the caller of the current status of the stream. a stream that is closed will throw an exception when this method is called. that enables the caller to know the condition of the stream before attempting to read from it. if a stream is at end-of-file, but not closed, then this method returns 0 bytes available. note: some nsiinputstream implementations automatically close() when end-of-file is reached; others do not. note: this method should not be used to determine the total size of a stream, even if the stream corresponds to a local file. moreover, since a stream may make availabl...
nsILocalFileMac
n creator code. if this app is missing, this will fail. it will first look for running application with the given creator. void inittoappwithcreatorcode( in ostype aappcreator ); parameters aappcreator the signature of the app. native code only!initwithcfurl init this object with a cfurlref. note: supported only for xp_macosx. note: if the path of the cfurl is /a/b/c, at least a/b must exist beforehand. void initwithcfurl( in cfurlref acfurl ); parameters acfurl the corefoundation url. native code only!initwithfsref init this object with an fsref. note: supported only for xp_macosx. void initwithfsref( [const] in fsrefptr afsref ); parameters afsref the native fsref. native code only!initwithfsspec obsolete since gecko 1.9.2 (firefox 3.6 / thunderbird 3.1 / fennec 1.0)this featu...
nsILoginInfo
value to assign to the passwordfield field. matches() tests to determine whether this login is loosely equivalent to another nsilogininfo object. the passwordfield and usernamefield values are ignored, and the password values may be optionally ignored. if one login's formsubmiturl is an empty string (but not null), it will be treated as a wildcard. a blank value indicates the login was stored before bug 360493 was fixed. boolean matches( in nsilogininfo alogininfo, in boolean ignorepassword ); parameters alogininfo the login to which to compare for equality. ignorepassword if true, do not examine the password value when matching. return value true if the two logins are equivilant or false if they're not. see also nsiloginmanager using nsiloginmanager ...
nsILoginManagerStorage
ostnames ); parameters count optional return in this parameter the number of disabled hostnames returned in the hostnames parameter. hostnames return in this parameter an array of all hostnames for which password saving is disabled. getallencryptedlogins() fetch all logins in the login manager. an array is always returned; if there are no logins the array is empty. this does not decrypt logins before returning the array. void getallencryptedlogins( out unsigned long count, optional [retval, array, size_is(count)] out nsilogininfo logins ); parameters count optional the number of elements in the array. logins an array of nsilogininfo objects. getalllogins() implement this method to return a list of all logins in the login store. void getalllogins( out unsigned long count, optional [...
nsIMessageListenerManager
[optional] in boolean listenwhenclosed); parameters messagename a string indicating the name of the message to listen for. listener an nsimessagelistener to invoke when a message is received. see nsimessagelistener for details of the message syntax. listenwhenclosed specify true to receive messages during the short period after a frame has been removed from the dom and before its frame script has finished unloading; this is false by default. this parameter only has an effect for frame message managers in the main process. an alternative method to listen for death of frame script is to use a message-manager-disconnect observer; see observer notifications :: message manager. removemessagelistener() undo an addmessagelistener() call; that is, calling this causes list...
nsIMicrosummary
r objects don't have a generator removeobserver() remove a microsummary observer from this microsummary. void removeobserver( in nsimicrosummaryobserver observer ); parameters observer the microsummary observer to remove. update() update the microsummary, first loading its generator and page content as necessary. if you want know when a microsummary finishes updating, add an observer before calling this method. void update(); see also microsummary topics creating a microsummary ...
nsIMicrosummaryService
to check. microsummary the microsummary to check. return value returns whether or not the microsummary is the current one for the bookmark. refreshmicrosummary() refreshes a microsummary, updating its value in the datastore and ui. if this method can refresh the microsummary instantly, it will. otherwise, it'll asynchronously download the necessary information (the generator and/or page) before refreshing the microsummary. callers should check the content property of the returned microsummary object to distinguish between sync and async refreshes. if its value is null, then it's an async refresh, and the caller should register itself as an nsimicrosummaryobserver via nsimicrosummary.addobserver() to find out when the refresh completes. nsimicrosummary refreshmicrosummary( in long long...
nsIModule
ponentmanager acompmgr ); parameters acompmgr the global component manager. return value indicates to the caller whether or not the component module can be unloaded. returning true is not a guarantee that the module will be unloaded. it constitues only willingness of the module to be unloaded. it is very important to ensure that no outstanding references to the module's code/data exist before returning true. returning false guaratees that the module will not be unloaded. if the component module is native (that is, as part of a dll), then this method may be called to determine whether or not the dll may be unloaded from memory. note: as of gecko 1.7, native component modules are never unloaded. getclassobject() obtains a class object from a nsimodule for a given cid and iid pair. this ...
nsIMsgAccountManagerExtension
has to be unique and defines the file name of the property file and the xul page as well as the name of the localized string contained in the property file. this attribute is readonly! chromepackagename acstring chrome package, where the files for the new panel are located. this is usually guid of the id of the addons which adds the new panel. this attribute is readonly! methods showpanel() before displaying a panel in the account manager this method is triggered. boolean showpanel( in nsimsgincomingserver server ); parameters server the account for which the panel should be displayed. return value a true indicates, that the account manager can display the panel for the given account, while false prevents the panel to be loaded. see also nsimsgaccountmanager building an account ...
nsINavBookmarksService
ing getkeywordforuri( in nsiuri auri ); parameters auri the uri whose keyword is to be retrieved. return value returns the keyword for the given uri. getremovefoldertransaction() this method retrieves an undo-able transaction for removing a folder from the bookmarks tree. this method exists because complex delete->undo operations rely on recreated folders to have the same id they had before they were deleted, so that any other items deleted in different transactions can be re-inserted correctly. this provides a safe encapsulation of this functionality without exposing the ability to recreate folders with specific ids (potentially dangerous if abused by other code!) in the public api. nsitransaction getremovefoldertransaction( in long long aitemid ); parameters aitemid the i...
nsINavHistoryResult
f, potentially causing unwanted additional work. when you close the root node the result will stop observing changes, so it is good practice to close the root node when you are done with a result, since that will avoid unwanted performance hits. read only. sortingannotation autf8string the annotation to use in sort_by_annotation_* sorting modes; you must set this value before setting the sortingmode attribute. sortingmode unsigned short specifies the sorting mode for the result. this value must be one of nsinavhistoryqueryoptions.sort_by_*. changing this value updates the corresponding options for the result so that reusing the current options and queries will always return results based on the current view. suppressnotific...
nsINavHistoryResultObserver
unsigned long anewindex ); parameters anode the moved node. aoldparent the node's old parent. aoldindex the node's index in the old parent. anewparent the node's new parent. anewindex the node's index in the new parent. noderemoved() called when a item is removed from a container. the item may be a container or a leaf. this method is called after the item has been removed from the parent, but before any other action is taken (including zeroing out the item's parent reference). void noderemoved( in nsinavhistorycontainerresultnode aparent, in nsinavhistoryresultnode aitem, in unsigned long aoldindex ); parameters aparent the container from which the item was removed. aitem the item that was removed from the container. it may be either a container or a leaf. aoldindex the index from...
nsINavHistoryResultViewer
ainerresultnode aparent, in nsinavhistoryresultnode anode, in unsigned long aoldindex ); parameters parent the container from which the item was removed. item the item that was removed from the container. it may be either a container or a leaf. oldindex the index from which the item was removed. remarks this method is called after the item has been removed from the parent, but before any other action is taken (including zeroing out the item's parent reference). nodetagschanged() called right after a node's tags have changed. void nodetagschanged( in nsinavhistoryresultnode anode ); parameters anode the node whose tags have changed. nodereplaced() called when a node is being replaced with another node at the same location. void nodereplaced(in nsinavhistorycont...
Component; nsIPrefBranch
be changed during the dispatch of nspref:changed notification. however, the observers are not guaranteed to be notified in any particular order, so you can't be sure whether the added/removed observer will be called during the notification when it is added/removed. it is possible to change preferences during the notification. it is not safe to change observers during this callback in releases before gecko 1.9. if you want a safe way to remove a preference observer, please use an nsitimer. see also nsiprefservice ...
nsIPrefBranch2
be changed during the dispatch of nspref:changed notification. however, the observers are not guaranteed to be notified in any particular order, so you can't be sure whether the added/removed observer will be called during the notification when it is added/removed. it is possible to change preferences during the notification. it is not safe to change observers during this callback in releases before gecko 1.9. if you want a safe way to remove a preference observer, please use an nsitimer. ...
nsIPrintingPrompt
implement this service to display at least the print dialog and a print progress dialog or you may implement just one of the dialogs and pass back ns_error_not_implemented for any of the others. for the print dialog: you may stub out this service by having all the methods return ns_error_not_implemented. you can then fly you own dialog and then properly fill in the printsettings object before calling nsiwebbrowserprint's print method. if you stub out this service you must set "printsilent" to true, if you do not, printing will terminate and an error dialog will be displayed. mac: the gfx layer still supports default toolkit behavior for displaying the print dialog. if an embedder implemented service returns ns_error_not_implemented for "showprintdialog" the toolkit will displa...
nsIProfile
d in gecko 1.6 implemented by: @mozilla.org/profile/manager;1. to get access to the profile manager service: var profile = components.classes["@mozilla.org/profile/manager;1"] .getservice(components.interfaces.nsiprofile); note: this interface was used by seamonkey up through seamonkey 1.1 versions, which were based off gecko 1.8.1. however, it hasn't been used in firefox since before firefox 1.0. method overview void cloneprofile(in wstring profilename); void createnewprofile(in wstring profilename, in wstring nativeprofiledir, in wstring langcode, in boolean useexistingdir); void deleteprofile(in wstring name, in boolean candeletefiles); void getprofilelist(out unsigned long length, [retval, array, size_is(length)] out wstring profilenames...
nsIPromptService
elay_enable button_delay_enable causes the buttons to be initially disabled. they are enabled after a timeout expires. the implementation may interpret this loosely, as the intent is to ensure that the user does not click through a security dialog too quickly. strictly speaking, the implementation could choose to ignore this flag. a delay can be useful not only to give the user more time to think before acting, but also as a countermeasure against malicious web sites that intentionally create a race condition whereby the user intends to click or type a key responding, for example, to the web site's prompt but the security dialog pops up unexpectedly and its button is unintentionally activated. constant value description button_delay_enable 67108864 standard ...
nsIProtocolHandler
i ); parameters auri the uri for which to construct a channel. return value return the newly constructed channel. newuri() makes a uri object that is suitable for loading by this protocol, where the uri string is given as an utf-8 string. the caller may provide the charset from which the uri string originated, so that the uri string can be translated back to that charset (if necessary) before communicating with, for example, the origin server of the uri string. (many servers do not support utf-8 iris at the present time, so we must be careful about tracking the native charset of the origin server.) nsiuri newuri( in autf8string aspec, in string aorigincharset, in nsiuri abaseuri ); parameters aspec the uri string in utf-8 encoding. depending on the protocol's implementati...
nsIProtocolProxyService
from resolve/asyncresolve as well as from getfailoverforproxy. nsiproxyinfo getfailoverforproxy( in nsiproxyinfo aproxyinfo, in nsiuri auri, in nsresult areason ); parameters aproxyinfo the proxy that was unavailable. auri the uri that was originally passed to resolve/asyncresolve. areason the error code corresponding to the proxy failure. this value may be used to tune the delay before this proxy is used again. the proxy that was unavailable. return value an nsiproxyinfo object or null for a direct connection. exceptions thrown ns_error_not_available if there is no alternate proxy available. registerfilter() this method may be used to register a proxy filter instance. each proxy filter is registered with an associated position that determines the order in which the f...
nsIRequest
ific validation logic. this flag is used when browsing via history. it is not recommended for normal browsing as it may likely violate reasonable assumptions made by the server and confuse users. the following flags control the frequency of cached content validation when neither load_bypass_cache or load_from_cache are set. by default, cached content is automatically validated if necessary before reuse. note: these flags are intended for normal browsing, and they should therefore not apply to content that must be validated before each use. consider, for example, a http response with a "cache-control: no-cache" header. according to rfc2616, this response must be validated before it can be taken from a cache. breaking this requirement could result in incorrect and potentially undesirable s...
nsISelection2
crolls a region of the selection, so that it is visible in the scrolled view. void scrollintoview( in short aregion, in boolean aissynchronous, in short avpercent, in short ahpercent ); parameters aregion the region inside the selection to scroll into view (see selection region constants defined in nsiselectioncontroller). aissynchronous when true, scrolls the selection into view before returning. if false, posts a request which is processed at some point after the method returns. avpercent how to align the frame vertically. a value of 0 means the frame's upper edge is aligned with the top edge of the visible area. a value of 100 means the frame's bottom edge is aligned with the bottom edge of the visible area. for values in between, the point "avpercent" down the frame is pla...
nsISelectionController
selection_hidden 1 hidden displays selection. selection_on 2 selection_disabled 3 selection_attention 4 scroll constants constant value description scroll_synchronous 1<<1 if set scrolls the selection into view before returning. if not set, posts a request which is processed at some point after the method returns. scroll_first_ancestor_only 1<<2 if set, only the first ancestor will be scrolled into view. scroll_center_vertically 1<<4 if set, the specified location will be scrolled to the center of the view. methods native code only!characterex...
nsISelectionPrivate
crolls a region of the selection, so that it is visible in the scrolled view. void scrollintoview( in short aregion, in boolean aissynchronous, in short avpercent, in short ahpercent ); parameters aregion the region inside the selection to scroll into view (see selection region constants defined in nsiselectioncontroller). aissynchronous when true, scrolls the selection into view before returning. if false, posts a request which is processed at some point after the method returns. avpercent how to align the frame vertically. a value of 0 means the frame's upper edge is aligned with the top edge of the visible area. a value of 100 means the frame's bottom edge is aligned with the bottom edge of the visible area. for values in between, the point "avpercent" down the frame is pla...
nsISocketTransport
anonymous_connect 1 when this flag is set, the socket will not apply any credentials when establishing a connection. for example, an ssl connection would not send any client-certificates if this flag is set. disable_ipv6 2 when this flag is set, the socket will ignore any ipv6 addresses the host may offer and will o...
nsIStandardURL
la.org/network/standard-url;1"] .createinstance(components.interfaces.nsistandardurl); method overview void init(in unsigned long aurltype, in long adefaultport, in autf8string aspec, in string aorigincharset, in nsiuri abaseuri); attributes attribute type description mutable boolean control whether or not this url can be modified. protocol handlers can set this flag before handing out an url to ensure that it is not inadvertently modified. obsolete since gecko 1.9 constants these constants describe how to normalize an url. constant value description urltype_standard 1 blah:foo/bar => blah://foo/bar blah:/foo/bar => blah:///foo/bar blah://foo/bar => blah://foo/bar blah:///foo/bar => blah:///foo/bar urltype_authority 2 blah:foo/bar => blah://f...
nsIStyleSheetService
g type); constants constant value description 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 ...
nsIThread
olean haspendingevents() boolean processnextevent(in boolean maywait) attributes attribute type description prthread prthread the nspr thread object corresponding to the nsithread. read only. methods shutdown() shuts down the thread. this causes events to stop being dispatched to the thread, and causes any pending events to run to completion before the thread joins with the current thread (see pr_jointhread() for details). during the execution of this method call, events for the current thread may continue to be processed. warning: this method may not be called from the thread itself. instead, you must only call it from another thread (usually the thread that created it, or the main application thread). when this function returns, the...
nsIThreadObserver
() called after an event has been dispatched to the thread. this method may be called from any thread. note: it is valid to change the thread's observer during a call to this method. void ondispatchedevent( in nsithreadinternal thread ); parameters thread the nsithread on which the event was dispatched. onprocessnextevent() called by the nsithread method nsithread.processnextevent() before an event is processed. this method is only called on the target thread. it is valid to change the thread\'s observer during a call to this method. void onprocessnextevent( in nsithreadinternal thread, in boolean maywait, in unsigned long recursiondepth ); parameters thread the nsithread on which the event is going to be processed. maywait true if the method is allowed to block the...
nsITraceableChannel
rowser tab that made the request) with your own implementation (see "implementing nsistreamlistener" below). after that your nsistreamlistener implementation will get the response data and will be able to pass the data on to the original nsistreamlistener (possibly modifying it). see nsitraceablechannel, intercept http traffic for a more detailed description with code samples. see modify url before loading page in firefox for an overview of how to modify a request before it is made. method overview nsistreamlistener setnewlistener(in nsistreamlistener alistener); methods setnewlistener() replaces the channel's current listener with a new one, returning the listener previously assigned to the channel. nsistreamlistener setnewlistener( in nsistreamlistener alistener ); ...
nsITransaction
usly executed transaction to merge. return value missing description redotransaction() executes the transaction again. can only be called on a transaction that was previously undone. in most cases, the redotransaction method will actually call the dotransaction() method to execute the transaction again. void redotransaction(); parameters none. undotransaction() restores the state to what it was before the transaction was executed. void undotransaction(); parameters none. see also nsitransactionlist nsitransactionlistener nsitransactionmanager ...
nsITreeColumns
rycolumn(); parameters none. return value the primary nsitreecolumn. getsortedcolumn() nsitreecolumn getsortedcolumn(); parameters none. return value a nsitreecolumn. invalidatecolumns() this method is called whenever a treecol is added or removed and the column cache needs to be rebuilt. void invalidatecolumns(); parameters none. restorenaturalorder() restore the original order of the columns before the user moved them. void restorenaturalorder(); parameters none. see also nsitreecolumn ...
nsIURI
). note: some characters may be escaped. port long the uri's port. a port value of -1 corresponds to the protocol's default port (for example -1 implies port 80 for http uris). exceptions thrown ns_error_failure if port is not applicable to the uri scheme (e.g. about:blank) prepath autf8string the prepath returns the string before the path (such as "scheme://user:password@host:port"). this is related to the web origin concept of rfc6454. this is useful for authentication, managing sessions, or for checking the origin of an uri to prevent cross-site scripting attacks while using methods such as window.postmessage(). note: some characters may be escaped. read only. ref autf8string returns th...
nsIUTF8ConverterService
v when there is no decoder for acharset or error code of nsiunicodedecoder in case of conversion failure. converturispectoutf8() ensure that aspec (after url-unescaping it) is encoded in utf-8. if not, convert it to utf-8, assuming it's encoded in acharset, and return the result. make sure that all characters outside us-ascii in your input spec are url-escaped if your spec is not in utf-8 (before url-escaping) because the presence of non-ascii characters is blindly regarded as an indication that your input spec is in unescaped utf-8 and it will be returned without further processing. no valid spec going around in mozilla code would break this assumption. autf8string converturispectoutf8( in acstring aspec, in string acharset ); parameters aspec an url-escaped uri spec to ensure its ...
nsIUpdate
urityupdate boolean true if the update is a security update. if the update is a security update, a more seriously-worded user interface message is used to present the update to the user. licenseurl astring the url to an html fragment that contains a license for the update. if this is specified, the user is shown the license file after they choose to install the update, and they must agree to it before the download begins. name astring the name of the update, in the form "application_name update_version" patchcount unsigned long the number of patches supplied by this update. read only. platformversion astring the toolkit version of this update. previousappversion astring the application version prior to the application being updated. selectedpatch nsiupdatepatch the currently select...
nsIWebBrowserChrome3
embedding/browser/webbrowser/nsiwebbrowserchrome3.idlscriptable an extension to nsiwebbrowserchrome2. 1.0 66 introduced gecko 2.0 inherits from: nsiwebbrowserchrome2 last changed in gecko 2.0 (firefox 4 / thunderbird 3.3 / seamonkey 2.1) method overview astring onbeforelinktraversal(in astring originaltarget, in nsiuri linkuri, in nsidomnode linknode, in prbool isapptab); methods onbeforelinktraversal() determines the appropriate target for a link. astring onbeforelinktraversal( in astring originaltarget, in nsiuri linkuri, in nsidomnode linknode, in prbool isapptab ); parameters originaltarget the original link target. linkuri link destination uri. linknode link dom node. isapptab whether or not the link ...
nsIWebNavigation
ntermediate proxy caches should be bypassed (that is, that the content should be loaded from the origin server). load_flags_charset_change 1024 this flag specifies that a reload was triggered as a result of detecting an incorrect character encoding while parsing a previously loaded document. load_flags_stop_content 2048 if this flag is set, stop() will be called before the load starts and will stop both content and network activity (the default is to only stop network activity). effectively, this passes the stop_content flag to stop(), in addition to the stop_network flag. load_flags_from_external 4096 a hint this load was prompted by an external program: take care! load_flags_allow_third_party_fixup 8192 this flag specifies th...
nsIWebProgressListener2
s. for example, via a <meta http-equiv="refresh"> or an http refresh: header. boolean onrefreshattempted( in nsiwebprogress awebprogress, in nsiuri arefreshuri, in long amillis, in boolean asameuri ); parameters awebprogress the nsiwebprogress instance that fired the notification. arefreshuri the new uri that awebprogress has requested redirecting to. amillis the delay (in milliseconds) before refresh. asameuri true if awebprogress is requesting a refresh of the current uri. false if awebprogress is requesting a redirection to a different uri. return value true if the refresh may proceed. false if the refresh should be aborted. ...
nsIWindowsShellService
starting key, using the constants defined above. asubkeyname the sub key to locate. avaluename the value to locate in the sub key. the empty string returns the default value of the sub key. return value the value of the specified sub key/value, truncated to 4096 bytes. restorefilesettings() obsolete since gecko 1.9 (firefox 3) restores system settings to what they were before firefox modified them. void restorefilesettings( in boolean aforallusers ); parameters aforallusers whether or not firefox should restore settings for all users on a multi-user system. shortcutmaintenance() provides the shell service an opportunity to do some win7+ shortcut maintenance needed on initial startup of the browser. void shortcutmaintenance(); parameters none. ...
nsIXMLHttpRequestEventTarget
avascript function object that gets invoked when the operation is completed for any reason; it will always follow a an abort, error, or load event. onloadstart nsidomeventlistener a javascript function object that gets invoked exactly once when the operation begins. onprogress nsidomeventlistener a javascript function object that gets invoked zero or more times, after the loadstart event, but before any abort, error, or load events occur. handling the events when the handler functions for these events are called, they receive as a parameter a progressevent, which implements the nsidomprogressevent interface. see also using xmlhttprequest xmlhttprequest nsixmlhttprequest nsidomprogressevent ...
nsIXPCScriptable
implementations may skip writing to *_retval unless they want to return pr_false. js/src/xpconnect/idl/nsixpcscriptable.idlnot scriptable please add a summary to this article. ...
nsIXULBuilderListener
: nsisupports last changed in gecko 1.7 method overview void didrebuild(in nsixultemplatebuilder abuilder); void willrebuild(in nsixultemplatebuilder abuilder); methods didrebuild() called after a template builder has rebuilt its content. void didrebuild( in nsixultemplatebuilder abuilder ); parameters abuilder the template builder that has rebuilt the content. willrebuild() called before a template builder rebuilds its content. void willrebuild( in nsixultemplatebuilder abuilder ); parameters abuilder the template builder that rebuilds the content. example create an object which implements nsixulbuilderlistener: var mylistener = { queryinterface: function(aiid) { if (aiid.equals(components.interfaces.nsixulbuilderlistener) || aiid.equals(components.interfaces.n...
nsIXULTemplateBuilder
urce anode, in nsiatom atag ); parameters anode node to check. atag tag that must match. return value returns true if the node has content generated for it; otherwise returns false. addrulefilter() adds a rule filter for a given rule, which may be used for specialized rule filtering. any existing filter on the rule is removed. the default conditions specified inside the <rule> tag are applied before the rule filter is applied, meaning that the filter may be used to further filter out results but not reaccept results that have already been rejected. void addrulefilter( in nsidomnode arule, in nsixultemplaterulefilter afilter ); parameters arule the rule to apply the filter to. afilter the filter to add. native code only!init called to initialize a xul content builder on a particular ro...
nsIXmlRpcClient
ted. constants constant type description int unsigned long nsisupportsprint32 boolean unsigned long nsisupportsprbool string unsigned long nsisupportscstring double unsigned long nsisupportsdouble datetime unsigned long nsisupportsprtime array readonly unsigned long nsisupportsarray struct readonly unsigned long nsisupportsdictionary methods init() set server url. call this before using this object void getdata ( in string serverurl ) ; parameters serverurl url of server side object on which methods should be called setauthentication() set authentication info if needed. both parameters must be specified for authentication to be enabled void setauthentication ( in string username, in string password ) ; parameters username username to be used if as...
nsIZipReader
on many but not all invalid apattern values. getcertificateprincipal() returns an object describing the entity which signed an entry. parsemanifest must be called first. if aentryname is an entry in the jar, getinputstream() must be called after parsemanifest. if aentryname is an external file which has meta-information stored in the jar, verifyexternalfile (not yet implemented) must be called before getprincipal. nsiprincipal getcertificateprincipal( in string aentryname ); parameters aentryname missing description return value an nsiprincipal. example demonstrating this function: list contents of xpi and read file contents getentry() returns a nsizipentry describing a specified zip entry. nsizipentry getentry( in autf8string zipentry ); parameters zipentry the zip ...
nsIZipReaderCache
lose has been called on the shared nsizipreader, this method will return the closed nsizipreader nsizipreader getzip( in nsifile zipfile ); parameters zipfile the zip file. return value the nsizipreader for the given zip file. init() initializes a new zip reader cache. void init( in unsigned long cachesize ); parameters cachesize the number of released entries to maintain before beginning to throw some out. the number of outstanding entries can be much greater than this number, this is the count for those otherwise unused entries. see also nsizipreader ...
nsMsgSearchOp
is also applies */ const nsmsgsearchopvalue islowerthan = 8; const nsmsgsearchopvalue beginswith = 9; const nsmsgsearchopvalue endswith = 10; const nsmsgsearchopvalue soundslike = 11; /* for ldap phoenetic matching ...
nsIAbCard/Thunderbird3
may return inaccurate results. boolean equals(in nsiabcard card) parameters card the card you are comparing with. return value true if the cards are the same. generatephoneticname() generate a phonetic name from the card, using the firstname and lastname values. astring generatephoneticname(in boolean alastnamefirst) parameters alastnamefirst set to true to put the last name before the first. return value a string containing the generated phonetic name. ...
nsMsgSearchOpValue
is also applies */ 160 const nsmsgsearchopvalue islowerthan = 8; 161 162 const nsmsgsearchopvalue beginswith = 9; 163 const nsmsgsearchopvalue endswith = 10; 164 165 const nsmsgsearchopvalue soundslike = 11; /* for ldap ...
Performance
on (by default). in order to keep the cache active between transactions, you needed to have a second connection with a 'dummy' (and schema changing) transaction. that is not needed now. you can control the size of the memory cache using the cache_size pragma. this value controls the number of pages of the file that can be kept in memory at once. the page size can be set using the page_size pragma before any operations have been done on the file. you can see an example of setting the maximum cache size to be a percentage of memory in nsnavhistory::initdb in toolkit/components/places/src/nsnavhistory.cpp. sharding the cache between connections by default, storage enables the sqlite shared-cache mode which makes multiple connections to the same database share the same cache. the cache is threadsafe...
Troubleshooting XPCOM components registration
also use the profiling feature of dependency walker to view failed module loads while running your application. open the profile menu and select start profiling.... in the dialog that appears, you can provide command line parameters and click ok to start the application. you will see any modules that failed to load in the module list. note: you should delete compreg.dat from your profile before doing this. note that even your version of msvc may matter; your test machine may not have the c runtime libraries (msvcr70.dll / msvcp70.dll for msvc 7.0, and similarly named files for 7.1 and 8.0) available. this even means that if you are using a component stub, the stub needs to be compiled using a version which the machine does support; most likely this means msvc 6.0. i...
Using IndexedDB in chrome
this method was removed in firefox 33. ...
Frequently Asked Questions
r->()" ns_precondition "you can't dereference a null nscomptr with operator*()" other issues printf("%x\n", mynscomptr); can cause the program to crash on sigill (illegal instruction), and not on the line with the printf, which can make it tricky to figure out. for debugging purposes you can write printf("%x\n", mynscomptr.get()); how do i... initialize an nscomptr? release an nscomptr before it goes out of scope? assign 0 into it. whenever an nscomptr takes on a new value, it always releases its old value, if any. assigning in the value 0 is just like assigning in a raw pointer that happens to be null. the old referent will be released. [see initialization and assignment for more details] you should note, though, that there is a small performance penalty for this. the nscomptr will...
Using nsCOMPtr
just keep reading. you'll know when to stop. ...
Using nsIDirectoryService
ass it to ns_initembedding, and it will be installed. if you are not using ns_initembedding, you will have to construct it and register it yourself using nsidirectoryservice.registerprovider(). if you are registering it yourself it is very important to register it immediately after calling ns_initxpcom. there are things in the startup process that need these locations at a very early point - even before registering components. if you want to use mpfilelocprovider, or something like it, to provide one fixed profile, just construct it and call its initialize method - it will register itself. again, if you do this, do not initialize the profile service - it's either one or the other. related pages code_snippets:file_i/o original document information authors: conrad carlen, doug turner la...
XPCOM ownership guidelines
g it. you don't own an object because you need it. in fact often you own it because it needs you. if you own it, it shouldn't own you. even transitively. or put another way: the ownership graph for any system should be acyclic. anytime there is a cycle of ownership, there is a situation that isn't automatically handled by destructors. special code must be provided and called to break the cycle before the participants can be individually released. you don't need to own it if it's lifetime is guaranteed to be longer than yours. as for instance, when it owns you. parents own their children (and not the reverse). though parents may not need to own their children. for instance, a tree may own all the nodes that are in it. all the nodes in the tree point to each other with non-owning pointers. ...
Xptcall Porting Guide
requires the callee to clean up the stack, so it is imperative that the interface information scheme allow the code to determine the correct stack pointer fixup for return without fail, else the process will crash. i opted to use inline assembler for the gcc linux x86 port. i ended up with larger stubs than i would have preferred rather than battle the compiler over what would happen to the stack before my asm code began running. i believe that the non-assembly parts of these files can be copied and reused with minimal (but not zero) platform specific tweaks. feel free to copy and paste as necessary. please remember that safety and reliability are more important than speed optimizations. this code is primarily used to connect xpcom components with javascript; function call overhead is a tiny par...
XPCOM
ne() nsifile.using nsipasswordmanagertechnical review completed.using nsisimpleenumeratorusing the clipboardthis section provides information about cutting, copying, and pasting to and from the clipboard.using the gecko sdkweak referencein xpcom, a weak reference is a special object that contains a pointer to an xpcom object, but doesnot keep that object alive. ...
XPIDL Syntax
Mozilla › Tech › XPIDL › Syntax
gle line feed as a newline, and not carriage returns (although xpidl begs to differ). additionally, the use of both c-style (/* ... */) and c++-style (// ... end-of-line) comments are permitted between any two tokens. some productions can only occur at the beginning of lines; to simplify the grammar, i will not mention them in the grammar, especially since they are handled as a preprocessing step before the idl source code is actually parsed. a `%{' that appears at the beginning of a line is the start of a raw code fragment, which extends until the end of a line that begins with `%}'. text inside raw code fragments are not otherwise parsed by xpidl directly. this may be followed by the language, as in `%{c++', to output the raw fragment only in the specified language. a `#include "file"' line...
XUL Overlays
Mozilla › Tech › XUL › Overlays
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. inserting the following processing instruction before the doctype declaration in a base file tells the layout engine to load the named overlay file: <?xul-overlay href="chrome://component/content/componentoverlay.xul"?> where component is the name of the package being overlayed (e.g., chrome://navigator/content/navigatoroverlay.xul). the layout engine loads any overlay files and then flows the resulting xul document, so problems associated with incr...
Testing Mozilla code
these articles will help you master (and continue to excel at) testing mozilla code. asan nightly projectthe asan nightly project involves building a firefox nightly browser with the popular addresssanitizer tool and enhancing it with remote crash reporting capabilities for any errors detected.clang static analysisthis document is split in two parts. ...
Index
(there was discussion of shipping with a default file) on spam detection, the user can choose to move spam to a special "junk" folder the user can configure junk mail can be automatically purged from the "junk" folder to analyze a message for spam, we need the entire message, not just the headers. spam detection happens after filters are run white listing happens after filters, but before spam detection the purge code is implemented as a search of the "junk" folder, looking for "old" message that have the proper junk status. when does purging happens? elaborate on the mime changes that were made for spam currently, spam filtering is does not work for news, but it would be possible to add support for this. (there is a bug on it.) 51 the libmime module ...
Mail and RDF
warning: the content of this article may be out of date. it was imported from mozilla.org and last updated in 1999. mozilla mail exposes many of it's data structures to rdf through a few datasources. this allows exposure of mailnews-specific data to user interface using rdf templates. you should learn about rdf before reading this document or you will be hopelessly confused. overview of mail rdf graph the root resource for all accounts, folders and messages is the rdf resource named msgaccounts:/. from this resource, you can follow a number of arcs to find servers, folders, and finally messages. eventually we'll probably hang mail filters, annotations, etc, off of nodes in the graph. here is an example of how this might be set up: in this tree-style representation of an rdf...
Spam filtering
re was discussion of shipping with a default file). on spam detection, the user can choose to move spam to a special "junk" folder. the user can configure junk mail can be automatically purged from the "junk" folder. to analyze a message for spam, we need the entire message, not just the headers. spam detection happens after filters are run. white listing happens after filters, but before spam detection. the purge code is implemented as a search of the "junk" folder, looking for "old" message that have the proper junk status. when does purging happens? elaborate on the mime changes that were made for spam. currently, spam filtering is does not work for news, but it would be possible to add support for this. (there is a bug on it.). initial state user acti...
The libmime module
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 to define a function which will finish up any initialization of the class object that needs to happen before the first time it is instantiated. its name must be of the form "<class>initialize", and it should initialize the various method slots in the class as appropriate. any methods or class variables which this class does not wish to override will be automatically inherited from the parent class (by virtue of its class-initialization function having been run first.) each class object will only be i...
Adding items to the Folder Pane
ng on these additional items has no effect. however, the complete example file includes code to display the number selected in thunderbird's main viewing pane, when such a number is selected in the folder pane. a note about the initial rebuild when thunderbird first starts up, the folder pane does an initial rebuild to get the first data it should display. unfortunately, this rebuild will occur before an extension's "load" event fires. thus, extensions may need to do manual insertions when this load event fires, if they want to add items to the initial display. add_code.js also includes code to accomplish this result. ...
Creating a Custom Column
o_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 column we add another treecol tag ("colreplyto") with the settings that we would like to use. don't forget to add in a splitter before the column to ensure that the user can easily resize and drag our column around. our replyto_col_overlay.xul should now contain something similar to this: <?xml version="1.0"?> <overlay id="sample" xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> <tree id="threadtree"> <treecols id="threadcols"> <splitter class="tree-splitter" /> <treecol id="colrepl...
Theme Packaging
order to be shown in firefox's themes window. theme file layout thunderbird themes are packaged in an xpi file with the following structure: theme.xpi: install.rdf preview.png icon.png chrome/ browser/files communicator/files global/files mozapps/files ... you must have a top-level chrome.manifest file which registers the chrome for the theme (as before) and also an install.rdf manifest that specifies metadata that is displayed in the appearance section of the add-ons manager. preview.png is a preview image which will show when double-clicked on a theme in the appearance section of the add-ons manager. it can be any size. icon.png is a 32x32 (max. 48x48) png (may contain alpha transparency) which will show up in the appearance section of the a...
Using the Mozilla symbol server
kback.exe failed - built without debugging information. symchk: helper.exe failed - built without debugging information. symchk: failed files = 4 symchk: passed + ignored files = 179 downloading symbols on linux / mac os x if you are on linux and running gdb 7.9 or newer, you can use this gdb python script to automatically fetch symbols. you will need to source this script before loading symbols (the part where it spends a few seconds loading each .so when you attach gdb). if you want to reload symbols, you can try: nosharedlibrary sharedlibrary 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...
Working with windows in chrome code
romewindow) – the same type as the window variable. technically speaking, it implements a number of interfaces, including nsidomjswindow and nsidomwindow, but it also contains the user-defined properties for global variables and functions of the window. so, for example, to access the dom document corresponding to the window, you can use win.document. note however, that the open() call returns before the window is fully loaded, so some calls, like win.document.getelementbyid() will fail. to overcome this difficulty, you can move the initialization code to a load handler of the window being opened or pass a callback function, as described below. you can get a window object from a document using document.defaultview. content windows when a xul window contains a widget capable of displaying a...
Declaring and Using Callbacks
hen the exception is thrown. warning: you must store a reference to the callback object as long as the native code might call it. if you don't, the gc might collect the relevant data structures, and the browser will crash when native code attempts to invoke your callback. arguments and return values js-ctypes automatically handles the conversion between javascript and c value representations. before the javascript callback function is invoked, js-ctypes converts the arguments passed by the caller to javascript values. where possible, js-ctypes will convert arguments to primitive types. for arguments of complex types, temporary cdata objects will be created. the return value is converted in a similar manner. ...
Memory Management
internals of an array will hold the referent objects alive. what won't keep objects alive it's important to note that getting direct access to the contents of a cdata object using address(), addressofelement(), or contents, will result in a cdata object that does not hold its referent alive. be sure to hold an explicit reference so that the referent object doesn't get into garbage collection, before you're done using it. closures you also need to be sure to retain references to any javascript code that native code may call back into. this should be obvious, but is important enough to be worth stating explicitly. when in doubt, malloc() when you need to keep data around, you can use malloc() to allocate it directly. this bypasses javascript's memory management and lets you handle memory m...
Standard OS Libraries
t = getcursorpos(point.address()); components.utils.reporterror(ret); components.utils.reporterror(point); lib.close(); resources for winapi githubgists :: noitidart / search · winapi - winapi js-ctypes snippets that can be copied and pasted to scratchpad com see using com from js-ctypes. unix unix based operating systems are linux, *bsd, solaris, etc. there is a star/asterik ("*") before "bsd" because this means the bsd family such as freebsd, openbsd (who by the way made ssh), netbsd, etc. gtk+ and qt are graphic frameworks, the graphic stack under unix is xorg (x11/x). gtk+ builds over x11. 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 co...
ctypes.open
there are two options: custom native file (dll, so, dylib, etc.) standard os libraries custom native file for this method, a native file must be created. a native file for use on unix systems is an so file, which is created and a c function called add() is written. int add(int a, int b) { return a + b; } to make this a shared library, a native file which can be loaded and used from js-ctypes, compile it with these commands: gcc -fpic -c mycfuntionsforunix.c gcc -shared -o mycfuntionsforunix.so mycfuntionsforunix.o a file named mycfuntionsforunix.so is successfully created. ...
Using js-ctypes
this is as simple as including the following line of code in the desired javascript scope: components.utils.import("resource://gre/modules/ctypes.jsm") loading a native library once you've imported the code module, you can call the ctypes.open() method to load each native library you wish to use. ...
Plug-in Basics - Plugins
es, description, file extensions, and the current state (enabled or disabled) of the plug-in for each mime type assigned to it. notice in view-source that this information is simply gathered from the javascript. because plug-ins are platform-specific, you must port them to every operating system and processor platform upon which you want to deploy your plug-in. plug-ins and helper applications before plug-ins, there were helper applications. a helper application is a separate, free-standing application that can be started from the browser. like a plug-in, the browser starts a helper application when the browser encounters a mime type that is mapped to it. unlike a plug-in, a helper application runs separately from the browser in its own application space and does not interact with the browser...
URLs - Plugins
g nntp access) locates usenet news groups or individual usenet articles; alternate to news. prospero (prospero directory service) locates a resource on a prospero directory server. telnet (reference to interactive sessions) locates an interactive service. wais (wide area information servers) locates wais databases and their documents. wysiwyg placed before another url; displays a page that javascript has updated using document.write. for more information, see rfc 3986, "uniform resource identifier (uri): generic syntax", and the iana uri scheme registry. getting urls posting urls getting urls to retrieve a url and display it on a specified target page, use the npn_geturl, npn_geturlnotify, and npp_urlnotify functions. this section des...
Version, UI, and Status Information - Plugins
parameter is the current plug-in instance, that is, the one that the status message belongs to. in the message parameter, pass the string you want to display on the status line. the browser always displays the last status line message it receives, regardless of the message source. for this reason, your message is always displayed, but you have no control over how long it stays in the status line before another message replaces it. you should use a different method to display messages that the user needs to see, such as error messages. getting agent information a plug-in can check which browser is running on the user's current system. browsers communicate with http servers, which store agent software name, version, and operating system in a user_agent field. if you want to gather usage statist...
Plugin Roadmap for Firefox - Plugins
ng 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 for plugins (bug 1381916). 2019 in september 2019, firefox 69 will remove the "always activate" flash option so we always ask for user permission before activating flash on a website. 2020 in december 2020, flash support will be completely removed from consumer versions of firefox. adobe will stop shipping security updates for flash at the end of 2020. see also mozilla firefox october 2015 - npapi plugins in firefox july 2016 - reducing adobe flash usage in firefox july 2017 - firefox roadmap for flash end-of-life adobe flash novem...
Debugging service workers - Firefox Developer Tools
plication panel. when you open the application panel’s service workers view on a page that doesn't have a service worker registered, you'll get the following output shown: this gives you some advice on what to do if you don't have a service worker registered, and were perhaps expecting there to be one registered! let's start by troubleshooting this. getting your service worker to register before you can look at your service worker in action in the applications panel, you need to successfully register it. registration is done with a block of code along these lines, using the register() method: if('serviceworker' in navigator) { navigator.serviceworker .register('sw.js') .then(function() { console.log('service worker registered'); }); } if you get the path wrong, ...
Browser Console - Firefox Developer Tools
"<h1>this page has been eaten</h1>"; }, true); newtabbrowser.contentdocument.location.href = "https://mozilla.org/"; it adds a listener to the currently selected tab's load event 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. on windows, the following code will add a new item to the browser's main menu: var parent = window.document.getelementbyid("appmenuprimarypane"); var makethetea = gbrowser.ownerdocument.defaultview.document.createelementns("http://www.mozilla.o...
Examine, modify, and watch variables - Firefox Developer Tools
this feature isn't yet supported in the new debugger. if you need to use it, you can, for now, switch back to the old debugger by visiting about:config and setting the "devtools.debugger.new-debugger-frontend" preference to false. to see the docs for the old debugger, please visit debugger (before firefox 52). examine variables when the code has stopped at a breakpoint, you can examine its state in the variables pane of the debugger: variables are grouped by scope: in function scope you'll see the built-in arguments and this variables as well as local variables defined by the function like user and greeting. similarly, in global scope you'll see global variables you've defined, like greetme, as well as built-in globals like localstorage and console. each object can be expanded, ...
Debugger keyboard shortcuts - Firefox Developer Tools
cmd + shift + b ctrl + shift + b 1. by default, on some macs, the function key is remapped to use a special feature: for example, to change the screen brightness or the volume. see this guide to using these keys as standard function keys. to use a remapped key as a standard function key, hold the function key down as well (so to open the profiler, use shift + function + f5). note: before firefox 66, the combination ctrl + shift + s on windows and linux or cmd + opt + s on macos would open/close the debugger. from firefox 66 and later, this is no longer the case. global shortcuts these shortcuts work in all tools that are hosted in the toolbox. command windows macos linux increase font size ctrl + + cmd + + ctrl + + decrease f...
Using the Debugger map scopes feature - Firefox Developer Tools
in the sources panel on the left and then set a breakpoint at line 102 in the increment function. when you click the increment button on the page and hit the breakpoint, an additional section is added to the right-hand panel below the call stack to display variables mapped from the original scope, like this: as useful as this is, it would be even nicer if you could view the original code (before it was packages into the "bundle.js" file. right-click on the source code and the context menu now includes an option to jump to original location as shown below. click jump to original location. the debugger opens the file "increment.js" so you can view the original code. notice that your breakpoint is set here in the original code as it was in the corresponding line in the "bundle.js" ...
Debugger - Firefox Developer Tools
t may have the following properties: class if present, only return objects whose internal [[class]]’s name matches the given string. note that in some cases, the prototype object for a given constructor has the same [[class]] as the instances that refer to it, but cannot itself be used as a valid instance of the class. code gathering objects by class name may need to examine them further before trying to use them. all properties of query are optional. passing an empty object returns all objects in debuggee globals. unlike findscripts, this function is deterministic and will never return debugger.objects referring to previously unreachable objects that had not been collected yet. clearbreakpoint(handler) remove all breakpoints set in this debugger instance that usehandler as th...
Debugger-API - Firefox Developer Tools
, and explain how the code entered the system, whether via a call to eval, a <script> element, or otherwise. a debugger.script points to the debugger.source from which it is derived. also omitted is the debugger’s debugger.memory instance, which holds methods and accessors for observing the debuggee’s memory use. all these types follow some general conventions, which you should look through before drilling down into any particular type’s specification. all shadow objects are unique per debugger and per referent. for a given debugger, there is exactly one debugger.object that refers to a particular debuggee object; exactly one debugger.frame for a particular stack frame; and so on. thus, a tool can store metadata about a shadow’s referent as a property on the shadow itself, and count o...
DevTools API - Firefox Developer Tools
er} - the zoom level such as 1.2. destroy() closes the toolbox. return value: a promise that is resolved once the toolbox is destroyed. events the toolbox object emits following events via the eventemitter interface. host-changed the host for this toolbox has changed. ready the toolbox is ready to use. select(toolid) a tool has been selected. this event is emitted before the corresponding {toolid}-selected event. {toolid}-init(frame) a tool is about to be loaded. the frame is the <iframe> element that has been created for the tool. {toolid}-build(panel) the frame for a tool has loaded and the toolpanel.build() method has been called but the asynchronous initialization has not started. the parameter is a toolpanel object. {toolid}-ready(panel) th...
JSON viewer - Firefox Developer Tools
to enable this feature in other release channels, set the devtools.jsonview.enabled preference to true. from firefox 53 onwards, the json viewer is also enabled by default in beta and the normal release version of firefox. firefox includes a json viewer. if you open a json file in the browser, or view a remote url with the content-type set to application/json, it is parsed and given syntax highlighting. arrays and objects are shown collapsed, and you can expand them using the "+" icons. the json viewer provides a search box that you can use to filter the json. ...
Dominators view - Firefox Developer Tools
pand the whole graph under a node. call stack in the toolbar at the top of the tool is a dropdown called "label by": by default, this is set to "type". however, you can set it instead to "call stack" to see exactly where in your code the objects are being allocated. this option is called "allocation stack" in firefox 46. to enable this, you must check the box labeled "record call stacks" before you run the code that allocates the objects. then take a snapshot, then select "call stack" in the "label by" drop-down. now the node's name will contain the name of the function that allocated it, and the file, line number and character position of the exact spot where the function allocated it. clicking the file name will take you to that spot in the debugger. sometimes you'll see "(no sta...
Network request list - Firefox Developer Tools
websocket connections use the ws button in the toolbar. you can filter by plain text (in which case the text is used to find partial matches; entering "for" will match any message that contains the word "for") or—as of firefox 75—using regular expressions (by writing the regexp bracketed within slashes; "/.+corp.*/" will look for any occurrence of "corp" which has at least one character before it and may or may not have any characters after it, for example). the third-party add-on websocket sniffer may be helpful as well. url use the filter urls box in the toolbar. you can focus it by clicking in the filter box, or by pressing ctrl + f (or cmd + f on a mac); then start typing. the list of network requests is filtered to include only requests that contain your f...
Page inspector 3-pane mode - Firefox Developer Tools
...
Work with animations - Firefox Developer Tools
ns animation inspector the page inspector's animations view displays animations in the page synchronized along a timeline, with a draggable widget you can use to move to any point in the timeline and see the page at that point. it displays animations created using css transitions, css @keyframes rules, or the web animations api. starting in firefox 48, it will show animations applied to the ::before and ::after pseudo-elements. to see how it works, we'll walk through an example. the box below contains a grayscale icon, representing firefox developer edition. if you click the icon, it enlarges and changes to color, and the name of the browser appears. click the icon again to reverse the effect. these animations are made using the web animations api. let's use the animation inspector to s...
UI Tour - Firefox Developer Tools
ed from most-specific to least-specific. see above. see examine and edit css for more details. layout view the layout view displays the box model of the page. if the page includes any sections using either the flexbox display model or css grids, this view shows the flexbox or grid settings used on the page. to learn more about the layout view, see examine and edit the box model. note that before firefox 50, the box model view did not appear in the "computed view" tab, but had its own tab. to learn more about the css declarations listed in this view, see examine computed css. changes view when you are editing in the rules view, you can see the changes you have made in the changes view. computed view the computed view shows you the complete computed css for the selected element (the...
Allocations - Firefox Developer Tools
ocating the most memory over the course of the profile. for performance this is important mostly because allocating a lot of memory, or making a lot of allocations, can trigger garbage collection. this in turn can hurt the responsiveness of a page. the allocations view is new in firefox 46. to enable the allocations view, you must check "record allocations" in the performance tool settings, before recording a profile. then record a profile as usual, and you will see a new tab labeled "allocations" in the toolbar: anatomy of the allocations view the allocations view looks something like this: the allocations view periodically samples allocations that are made over the recording. each row represents a function in which at least one allocation-sample was taken during the recording. it...
Intensive JavaScript - Firefox Developer Tools
rimes); } we're just running a (very inefficient) primality test 50 times, for some quite large numbers. using requestanimationframe in the first attempt at fixing this, we'll split up the function into a number of much smaller self-contained functions, and schedule each one using requestanimationframe(). requestanimationframe() tells the browser to run the given function in each frame, just before it performs a repaint. as long as each function is reasonably small, the browser should be able to keep inside its frame budget. it's pretty simple to split up calculateprimes(): we will just calculate primality for each number in a separate function: function dopointlesscomputationswithrequestanimationframe() { function testcandidate(index) { // finishing condition if (index == iter...
UI Tour - Firefox Developer Tools
about the flame chart, see the separate flame chart page. allocations the allocations view is new in firefox 46. the allocations view is like the call tree view, but for allocations: it shows you which functions in your page are allocating the most memory over the course of the profile. the allocations view only appears if you checked "record allocations" in the performance tool settings, before recording a profile: to learn much more about the allocations view, see the separate allocations page. ...
Web Console Helpers - Firefox Developer Tools
lename, the image file will be named with the following format: screen shot yyy-mm-dd at hh.mm.ss.png the command has the following optional parameters: command type description --clipboard boolean when present, this parameter will cause the screenshot to be copied to the clipboard. --delay number the number of seconds to delay before taking the screenshot. --dpr number the device pixel ratio to use when taking the screenshot. --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 ...
The JavaScript input interpreter - Firefox Developer Tools
. if you don't supply a filename, the image file will be named: screen shot yyy-mm-dd at hh.mm.ss.png the command has the following optional parameters: command type description --clipboard boolean when present, this parameter will cause the screenshot to be copied to the clipboard. --delay number the number of seconds to delay before taking the screenshot. --dpr number the device pixel ratio to use when taking the screenshot. --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 ...
Web Console UI Tour - Firefox Developer Tools
to say when the messages were logged. group similar messages: when enabled, similar types of messages are grouped together, with an indicator of the number of occurrences. enable autocompletion: when enabled, the javascript interpreter attempts to autocomplete while you type. instant evaluation: when enabled, the interpreter displays the evaluated results of an expression, when possible, before you press enter to submit it. message display pane this is where the messages appear, both those generated by the code in the page, and those generated by the commands entered on the command line. see console messages for a lot more detail on what the messages can contain. note: you can clear the contents of the console by entering the keyboard command ctrl + shift + l (windows, macos,...
Web Console remoting - Firefox Developer Tools
you can only get cached messages for page errors and console api calls. the reply looks like this: { "messages": [ ... ], "from": "conn0.console9" } each message in the array is of the same type as when we send typical page errors and console api calls. these will be explained in the following sections of this document. actor preferences to allow the web console...
Firefox Developer Tools
hat let you perform actions or change tool settings. this button only appears when there are multiple iframes on a page. click it to display a list of the iframes on the current page and select the one with which you want to work. click this button to take a screenshot of the current page. (note: this feature is not turned on by default and must be enabled in settings before the icon will appear.) toggles responsive design mode. opens the menu that includes docking options, the ability to show or hide the split console, and developer tools settings. the menu also includes links to the documentation for firefox web tools and the mozilla community. closes the developer tools page inspector view and edit page content an...
AbortController.abort() - Web APIs
this is able to abort fetch requests, consumption of any response body, and streams. syntax controller.abort(); parameters none. return value void. examples in the following snippet, we aim to download a video using the fetch api. we first create a controller using the abortcontroller() constructor, then grab a reference to its associated abortsignal object using the abortcontroller.signal property. when the fetch request is initiated, we pass in the abortsignal as an option inside the request's options object (see {signal}, below). ...
AbortController - Web APIs
ntroller.abortcontroller() constructor. communicating with a dom request is done using an abortsignal object. constructor abortcontroller() creates a new abortcontroller object instance. properties abortcontroller.signal read only returns a abortsignal object instance, which can be used to communicate with/abort a dom request. methods abortcontroller.abort() aborts a dom request before it has completed. this is able to abort fetch requests, consumption of any response body, and streams. examples in the following snippet, we aim to download a video using the fetch api. 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,...
Animation.oncancel - Web APIs
the oncancel property of the web animations api's animation interface is the event handler for the cancel event. the cancel event can be triggered manually with animation.cancel() when the animation enters the "idle" play state from another state, such as when the animation is removed from an element before it finishes playing creating a new animation that is initially idle does not trigger a cancel event on the new animation. syntax var cancelhandler = animation.oncancel; animation.oncancel = cancelhandler; value a function to be executed when the animation is cancelled, or null if there is no cancel event handler. examples if this animation is canceled, remove its element. animation.oncancel = function() { animation.effect.target.remove(); }; specifications specifica...
Attr.namespaceURI - Web APIs
Web › API › Attr › namespaceURI
syntax namespace = attribute.namespaceuri example in this snippet, an attribute is being examined for its localname and its namespaceuri. if the namespaceuri returns the xul namespace and the localname returns "browser", then the node is understood to be a xul <browser/>. ...
Attr.prefix - Web APIs
Web › API › Attr › prefix
syntax string = attribute.prefix examples the following logs "x" to the console. <div x:id="example" onclick="console.log(this.attributes[0].prefix)"/> notes this will only work when a namespace-aware parser is used, i.e. when a document is served with an xml mime type. this will not work for html documents. ...
Attr - Web APIs
Web › API › Attr
this is going away. createattribute() use element.setattribute() instead. createattributens() use element.setattributens() instead. getattributenode() use element.getattribute() instead. getattributenodens() use element.getattributens() instead. hasattributes() obsolete since gecko 21.0 this method now always returns false. haschildnodes() this method now always returns false. insertbefore() modify the value of attr.value instead. issupported() you shouldn't have been using this in the first place, so you probably don't care that this is going away. isequalnode() you shouldn't have been using this in the first place, so you probably don't care that this is going away. normalize() you shouldn't have been using this in the first place, so you probably don't care that this is g...
AudioBufferSourceNode.playbackRate - Web APIs
is a k-rate audioparam that defines the speed at which the audio asset will be played. a value of 1.0 indicates it should play at the same speed as its sampling rate, values less than 1.0 cause the sound to play more slowly, while values greater than 1.0 result in audio playing faster than normal. the default value is 1.0. when set to another value, the audiobuffersourcenode resamples the audio before sending it to the output. syntax audiobuffersourcenode.playbackrate.value = playbackrateproportion; value an audioparam whose value is a floating-point value indicating the playback rate of the audio as a decimal proportion of the original sampling rate. consider a sound buffer containing audio sampled at 44.1 khz (44,100 samples per second). let's see what a few values of playbackrate do:...
AudioContext.createMediaElementSource() - Web APIs
= new audiocontext(); var source = audioctx.createmediaelementsource(mymediaelement); parameters mymediaelement an htmlmediaelement object that you want to feed into an audio processing graph to manipulate. returns a mediaelementaudiosourcenode. example this simple example creates a source from an <audio> element using createmediaelementsource(), then passes the audio through a gainnode before feeding it into the audiodestinationnode for playback. when the mouse pointer is moved, the updatepage() function is invoked, which calculates the current gain as a ratio of mouse y position divided by overall window height. you can therefore increase and decrease the volume of the playing music by moving the mouse pointer up and down. note: you can also view this example running live, or view ...
AudioContext - Web APIs
the audiocontext interface represents an audio-processing graph built from audio modules linked together, each represented by an audionode. an audio context controls both the creation of the nodes it contains and the execution of the audio processing, or decoding. you need to create an audiocontext before you do anything else, as everything happens inside a context. it's recommended to create one audiocontext and reuse it instead of initializing a new one each time, and it's ok to use a single audiocontext for several different audio source and pipeline concurrently. <div id="interfacediagram" style="display: inline-block; position: relative; width: 100%; padding-bottom: 11.666666666666666%; vertical-align: middle; overflow: hidden;"><svg style="display: inline-block; position: absolute; t...
AudioNode.connect() - Web APIs
Web › API › AudioNode › connect
connecting to an audio input the most obvious use of the connect() method is to direct the audio output from one node into the audio input of another node for further processing. for example, you might send the audio from a mediaelementaudiosourcenode—that is, the audio from an html5 media element such as <audio>—through a band pass filter implemented using a biquadfilternode to reduce noise before then sending the audio along to the speakers. this example creates an oscillator, then links it to a gain node, so that the gain node controls the volume of the oscillator node. var audiocontext = window.audiocontext || window.webkitaudiocontext; var audioctx = new audiocontext(); var oscillator = audioctx.createoscillator(); var gainnode = audioctx.creategain(); oscillator.connect(gainnode)...
AudioProcessingEvent - Web APIs
iodata(), 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 each channel of the input buffer, and each sample in each channel, and add a small amount of white noise, before setting that result to be the output sample in each case. note: for a full working example, see our script-processor-node github repo (also view the source code.) var myscript = document.queryselector('script'); var mypre = document.queryselector('pre'); var playbutton = document.queryselector('button'); // create audiocontext and buffer source var audioctx = new audiocontext(); source...
AudioScheduledSourceNode.stop() - Web APIs
op() method on audioscheduledsourcenode schedules a sound to cease playback at the specified time. if no time is specified, then the sound stops playing immediately. each time you call stop() on the same node, the specified time replaces any previously-scheduled stop time that hasn't occurred yet. if the node has already stopped, this method has no effect. note: if a scheduled stop time occurs before the node's scheduled start time, the node never starts to play. syntax audioscheduledsourcenode.stop([when]); parameters when optional the time, in seconds, at which the sound should stop playing. this value is specified in the same time coordinate system as the audiocontext is using for its currenttime attribute. omitting this parameter, specifying a value of 0, or passing a negative va...
AudioScheduledSourceNode - Web APIs
. specifically, this interface defines the start() and stop() methods, as well as the onended event handler. you can't create an audioscheduledsourcenode object directly. instead, use the interface which extends it, such as audiobuffersourcenode, oscillatornode, and constantsourcenode. unless stated otherwise, nodes based upon audioscheduledsourcenode output silence when not playing (that is, before start() is called and after stop() is called). silence is represented, as always, by a stream of samples with the value zero (0). properties inherits properties from its parent interface, audionode. methods inherits methods from its parent interface, audionode, and adds the following methods: start() schedules the node to begin playing the constant sound at the specified time. if no time ...
BaseAudioContext.createScriptProcessor() - Web APIs
iodata(), 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 each channel of the input buffer, and each sample in each channel, and add a small amount of white noise, before setting that result to be the output sample in each case. note: for a full working example, see our script-processor-node github repo (also view the source code.) var myscript = document.queryselector('script'); var mypre = document.queryselector('pre'); var playbutton = document.queryselector('button'); // create audiocontext and buffer source var audioctx = new audiocontext(); source...
Battery Status API - Web APIs
the battery status api, more often referred to as the battery api, provides information about the system's battery charge level and lets you be notified by events that are sent when the battery level or charging status change. this can be used to adjust your app's resource usage to reduce battery drain when the battery is low, or to save changes before the battery runs out in order to prevent data loss. the battery status api extends window.navigator with a navigator.getbattery() method returning a battery promise, which is resolved in a batterymanager object providing also some new events you can handle to monitor the battery status. example in this example, we watch for changes both to the charging status (whether or not we're plugged in and charging) and for changes to the battery level...
BiquadFilterNode.getFrequencyResponse() - Web APIs
the getfrequencyresponse() method of the biquadfilternode interface takes the current filtering algorithm's settings and calculates the frequency response for frequencies specified in a specified array of frequencies. the two output arrays, magresponseoutput and phaseresponseoutput, must be created before calling this method; they must be the same size as the array of input frequency values (frequencyarray). syntax biquadfilternode.getfrequencyresponse(frequencyarray, magresponseoutput, phaseresponseoutput); parameters frequencyarray a float32array containing an array of frequencies, specified in hertz, which you want to filter. magresponseoutput a float32array to receive the computed magnitudes of the freqency response for each frequency value in the frequencyarray. for any freque...
BlobBuilder - Web APIs
oid append(in string data, [optional] in string endings); blob getblob([optional] in domstring contenttype); file getfile(in domstring name, [optional] in domstring contenttype); methods append() appends the contents of the specified javascript object to the blob being built. if the value you specify isn't a blob, arraybuffer, or string, the value is coerced to a string before being appended to the blob. void append( in arraybuffer data ); void append( in blob data ); void append( in string data, [optional] in string endings ); parameters data the data to append to the blob being constructed. endings specifies how strings containing \n are to be written out. this can be "transparent" (endings unchanged) or "native" (endings changed to match host os ...
Body.arrayBuffer() - Web APIs
Web › API › Body › arrayBuffer
nse stream and reads it to completion. it returns a promise that resolves with an arraybuffer. syntax response.arraybuffer().then(function(buffer) { // do something with buffer }); parameters none. return value a promise that resolves with an arraybuffer. examples playing music in our fetch array buffer live, we have a play button. when pressed, the getdata() function is run. note that before playing full audio file will be downloaded. if you need to play ogg during downloading (stream it) - consider htmlaudioelement: new audio("music.ogg").play(); in getdata() we create a new request using the request() constructor, then use it to fetch an ogg music track. we also use audiocontext.createbuffersource to create an audio buffer source. when the fetch is successful, we read an arraybu...
Body.bodyUsed - Web APIs
Web › API › Body › bodyUsed
etch request example (run fetch request live), we create a new request using the request() constructor, then use it to fetch a jpg. when the fetch is successful, we read a blob out of the response using blob(), put it into an object url using url.createobjecturl, and then set that url as the source of an <img> element to display the image. notice that we log response.bodyused to the console once before the response.blob() call and once after. this returns false before and true afterwards, as at that point the body has been read. html content <img class="my-image" src="https://udn.realityripple.com/samples/46/29059a2b39.png"> js content var myimage = document.queryselector('.my-image'); fetch('https://upload.wikimedia.org/wikipedia/commons/7/77/delete_key1.jpg').then(function(response) { ...
ByteLengthQueuingStrategy.ByteLengthQueuingStrategy() - Web APIs
the bytelengthqueuingstrategy() constructor creates and returns a bytelengthqueuingstrategy object instance. syntax var bytelengthqueuingstrategy = new bytelengthqueuingstrategy({highwatermark}); parameters {highwatermark} an object containing a highwatermark property. this is a non-negative integer defining the total number of chunks that can be contained in the internal queue before backpressure is applied. return value an instance of the bytelengthqueuingstrategy object. exceptions none. examples const queuingstrategy = new bytelengthqueuingstrategy({ highwatermark: 1 }); const readablestream = new readablestream({ start(controller) { ... }, pull(controller) { ... }, cancel(err) { console.log("stream error:", err); } }, queuingstrategy); var size = ...
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. ...
CSSPseudoElement - Web APIs
sing pseudo-elements, most modern browsers will automatically add quotation marks around text inside a <q> element. (a style rule may be needed to add quotation marks in older browsers.) the example below demonstrates the basic properties of the csspseudoelement object representing the opening quotation mark. const element = document.queryselector('q'); const csspseudoelement = element.pseudo('::before'); console.log(csspseudoelement.element); // outputs [object htmlquoteelement] console.log(csspseudoelement.type); // outputs '::before' specifications specification status comment css pseudo-elements level 4the definition of 'csspseudoelement' in that specification. working draft initial definition. ...
CSSStyleDeclaration.removeProperty() - Web APIs
tyledeclaration.removeproperty() method interface removes a property from 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. exceptions domexception no_modification_allowed_err: if the property or declaration block is read only. example the following javascript code removes the background-color css property from a selector rule: var declaration = document.stylesheets[0].rules[0].style; var oldvalue = declaration.removeproperty('background-color'); specifications specification sta...
CSSStyleRule.style - Web APIs
...
CSSStyleSheet.insertRule() - Web APIs
: ' + prop[1] + (prop[2] ? ' !important' : '') + ';\n'; } // insert css rule stylesheet.insertrule(selector + '{' + propstr + '}', stylesheet.cssrules.length); } } polyfill the below polyfill will correct the input of the arguments of insertrule() to standardize them in internet explorer 5–8. it supplements insertrule() with a function that separates the selector from the rules before sending the arguments to the default native insertrule(). (function(sheet_proto){ var originalinsertrule = sheet_proto.insertrule; if (originalinsertrule.length === 2){ // 2 mandatory arguments: (selector, rules) sheet_proto.insertrule = function(selectorandrule){ // first, separate the selector from the rule a: for (var i=0, len=selectorandrule.length, isescaped=0, newcharc...
Using the CSS Painting API - Web APIs
ples/csspaint/intro/worklet/boxbg.js'); while you can't play with the worklet's script, you can alter the custom property values to change the colors and width of the background image. adding complexity the above examples might not seem very exciting, as you could recreate them in a few different ways with existing css properties, e.g. by positioning some decorative generated content with ::before, or including background: linear-gradient(yellow, yellow) 0 15px / 200px 20px no-repeat; what makes the css painting api so interesting and powerful is that you can create complex images, passing variables, that automatically resize. let's take a look at a more complex paint example. registerpaint('headerhighlight', class { static get inputproperties() { return ['--highcolour']; } static ge...
Using the CSS Typed Object Model - Web APIs
tylemap(); the following examples reference allcomputedstyles: cssunparsedvalue the cssunparsedvalue represents custom properties: // cssunparsedvalue let unit = allcomputedstyles.get('--unit'); console.log( unit ) // cssunparsedvalue {0: " 1.2rem", length: 1} console.log (unit[0] ) // " 1.2rem" when we invoke get(), a custom property of type cssunparsedvalue is returned. note the space before the 1.2rem. to get a unit and value, we need a cssunitvalue, which we can retrieve using the cssstylevalue.parse() method on the cssunparsedvalue. let parsedunit = cssnumericvalue.parse( unit ); console.log( parsedunit ); // cssunitvalue {value: 1.2, unit: "rem"} console.log( parsedunit.unit ); // "rem" console.log( parsedunit.value ); // 1.2 cssmathsum although the <button> elemen...
Cache - Web APIs
Web › API › Cache
match() or fetch() operations. // note that a http error response (e.g. 404) will not trigger an exception. // it will return a normal response object that has the appropriate error code set. console.error(' error in fetch handler:', error); throw error; }); }) ); }); storing cookies in caches the fetch api requires set-cookie headers to be stripped before returning a response object from fetch(). so a response stored in a cache won't contain headers. specifications specification status comment service workersthe definition of 'cache' in that specification. working draft initial definition. ...
CacheStorage.delete() - Web APIs
caches.delete(cachename).then(function(boolean) { // your cache is now deleted }); parameters cachename the name of the cache you want to delete. return value a promise that resolves to true if the cache object is found and deleted, and false otherwise. examples in this code snippet we wait for an activate event, and then run a waituntil() block that clears up any old, unused caches before a new service worker is activated. here we have an array of cache names we want to keep (cachestokeep). we return the keys of the caches in the cachestorage object using cachestorage.keys, then check each key to see if it is in the array. if not, we delete it using delete(). this.addeventlistener('activate', function(event) { var cachestokeep = ['v2']; event.waituntil( caches.keys().the...
CacheStorage.keys() - Web APIs
Web › API › CacheStorage › keys
ccess cachestorage through the global caches property. syntax caches.keys().then(function(keylist) { //do something with your keylist }); parameters none. return value a promise that resolves with an array of the cache names inside the cachestorage object. examples in this code snippet we wait for an activate event, and then run a waituntil() block that clears up any old, unused caches before a new service worker is activated. here we have a whitelist containing the names of the caches we want to keep (cachewhitelist). we return the keys of the caches in the cachestorage object using keys(), then check each key to see if it is in the whitelist. if not, we delete it using cachestorage.delete(). then.addeventlistener('activate', function(event) { var cachewhitelist = ['v2']; event...
CanvasRenderingContext2D.beginPath() - Web APIs
ll this method when you want to create a new path. note: to create a new sub-path, i.e., one matching the current canvas state, you can use canvasrenderingcontext2d.moveto(). syntax void ctx.beginpath(); examples creating distinct paths this example creates two paths, each of which contains a single line. html <canvas id="canvas"></canvas> javascript the beginpath() method is called before beginning each line, so that they may be drawn with different colors. const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); // first path ctx.beginpath(); ctx.strokestyle = 'blue'; ctx.moveto(20, 20); ctx.lineto(200, 20); ctx.stroke(); // second path ctx.beginpath(); ctx.strokestyle = 'green'; ctx.moveto(20, 20); ctx.lineto(120, 120); ctx.stroke(); result ...
CanvasRenderingContext2D.bezierCurveTo() - Web APIs
syntax void ctx.beziercurveto(cp1x, cp1y, cp2x, cp2y, x, y); parameters cp1x the x-axis coordinate of the first control point. ...
CanvasRenderingContext2D.clearRect() - Web APIs
syntax void ctx.clearrect(x, y, width, height); the clearrect() method sets the pixels in a rectangular area to transparent black (rgba(0,0,0,0)). ...
CanvasRenderingContext2D.clip() - Web APIs
ne represents a clipping region shaped like a star. only those parts of the checkerboard pattern that are within the clipping region get drawn. note: be aware that the clipping region is only constructed from shapes added to the path. it doesn't work with shape primitives drawn directly to the canvas, such as fillrect(). instead, you'd have to use rect() to add a rectangular shape to the path before calling clip(). syntax void ctx.clip([fillrule]); void ctx.clip(path [, fillrule]); parameters fillrule the algorithm by which to determine if a point is inside or outside the clipping region. possible values: "nonzero": the non-zero winding rule. default rule. "evenodd": the even-odd winding rule. path a path2d path to use as the clipping region. examples a simple clippin...
CanvasRenderingContext2D.drawWindow() - Web APIs
probably want windowglobalparent.drawsnapshot from the parent process. syntax void ctx.drawwindow(window, x, y, w, h, bgcolor [, flags]); parameters window the window to render. x the x-axis coordinate of the window. y the y-axis coordinate of the window. w the width of the window. h the height of the window. bgcolor a domstring that specifies the color the canvas is filled with before the window is rendered into it. this color may be transparent/translucent. it is given as a css color string (for example, rgb() or rgba()). notes: if "rgba(0,0,0,0)" is used for the background color, the drawing will be transparent wherever the window is transparent. top-level browsed documents are usually not transparent because the user's background-color preference is applied, but ifra...
CanvasRenderingContext2D.font - Web APIs
the font property to specify a custom font weight, size, and family. html <canvas id="canvas"></canvas> javascript const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); ctx.font = 'bold 48px serif'; ctx.stroketext('hello world', 50, 100); result loading fonts with the css font loading api with the help of the fontface api, you can explicitly load fonts before using them in a canvas. let f = new fontface('test', 'url(x)'); f.load().then(function() { // ready to use the font in a canvas context }); specifications specification status comment html living standardthe definition of 'canvasrenderingcontext2d.font' in that specification. living standard ...
CanvasRenderingContext2D.globalAlpha - Web APIs
see also the chapter applying styles and color in the canvas tutorial. syntax ctx.globalalpha = value; options value a number between 0.0 (fully transparent) and 1.0 (fully opaque), inclusive. the default value is 1.0. values outside that range, including infinity and nan, will not be set, and globalalpha will retain its previous value. ...
CanvasRenderingContext2D.quadraticCurveTo() - Web APIs
syntax void ctx.quadraticcurveto(cpx, cpy, x, y); parameters cpx the x-axis coordinate of the control point. ...
CanvasRenderingContext2D.resetTransform() - Web APIs
to that matrix. const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); // draw a rotated rectangle ctx.rotate(45 * math.pi / 180); ctx.fillrect(60, 0, 100, 30); // reset transformation matrix to the identity matrix ctx.resettransform(); result continuing with a regular matrix whenever you're done drawing transformed shapes, you should call resettransform() before rendering anything else. in this example, the first two shapes are drawn with a skew transformation, and the last two are drawn with the identity (regular) transformation. html <canvas id="canvas"></canvas> javascript const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); // skewed rectangles ctx.transform(1, 0, 1.7, 1, 0, 0); ctx.fillstyle = 'gray'; ctx.fill...
CanvasRenderingContext2D - Web APIs
e matrix described by its arguments. canvasrenderingcontext2d.settransform() resets the current transform to the identity matrix, and then invokes the transform() method with the same arguments. canvasrenderingcontext2d.resettransform() resets the current transform by the identity matrix. compositing canvasrenderingcontext2d.globalalpha alpha value that is applied to shapes and images before they are composited onto the canvas. default 1.0 (opaque). canvasrenderingcontext2d.globalcompositeoperation with globalalpha applied this sets how shapes and images are drawn onto the existing bitmap. drawing images canvasrenderingcontext2d.drawimage() draws the specified image. this method is available in multiple formats, providing a great deal of flexibility in its use. pixel manipu...
Applying styles and colors - Web APIs
this method to create a canvaspattern object which is very similar to the gradient methods we've seen above. once we've created a pattern, we can assign it to the fillstyle or strokestyle properties. for example: var img = new image(); img.src = 'someimage.png'; var ptrn = ctx.createpattern(img, 'repeat'); note: like with the drawimage() method, you must make sure the image you use is loaded before calling this method or the pattern may be drawn incorrectly. a createpattern example in this last example, we'll create a pattern to assign to the fillstyle property. the only thing worth noting is the use of the image's onload handler. this is to make sure the image is loaded before it is assigned to the pattern. function draw() { var ctx = document.getelementbyid('canvas').getcontext('2d'...
Compositing and clipping - Web APIs
...
Drawing text - Web APIs
lues: start, end, 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. the following diagram from the whatwg demonstrates the various baselines supported by the textbaseline property. a textbaseline example edit the code below and see your changes update live in the canvas: ctx.font = '48px serif'; ctx.textbaseline = 'hanging'; ctx.stroketext('hello world', 0, 100); playable code <canvas id="canvas" width="400" height="200" class="playable-canvas"></canvas>...
Canvas tutorial - Web APIs
to use the <canvas> element to draw 2d graphics, starting with the basics. the examples provided should give you some clear ideas about what you can do with canvas, and will provide code snippets that may get you started in building your own content. first introduced in webkit by apple for the os x dashboard, <canvas> has since been implemented in browsers. today, all major browsers support it. before you start using the <canvas> element is not very difficult, but you do need a basic understanding of html and javascript. the <canvas> element is not supported in some older browsers, but is supported in recent versions of all major browsers. the default size of the canvas is 300 pixels × 150 pixels (width × height). but custom sizes can be defined using the html height and width property. in ...
Clients.claim() - Web APIs
Web › API › Clients › claim
esults in your service worker controlling pages that loaded regularly over the network, or possibly via a different service worker. syntax await clients.claim(); parameters none. return value a promise that resolves to undefined. example the following example uses claim() inside service worker's "activate" event listener so that clients loaded in the same scope do not need to be reloaded before their fetches will go through this service worker. self.addeventlistener('activate', event => { event.waituntil(clients.claim()); }); specifications specification status comment service workersthe definition of 'claim()' in that specification. working draft initial definition. ...
Clipboard.read() - Web APIs
Web › API › Clipboard › read
d can return arbitrary data, such as images. this method can also return text. to read from the clipboard, you must first have the "clipboard-read" permission. note: the asynchronous clipboard and permissions apis are still in the process of being integrated into most browsers, so they often deviate from the official rules for permissions and the like. be sure to review the compatibility table before using these methods. syntax var promise = navigator.clipboard.read(); parameters none. return value a promise that resolves with a datatransfer object containing the clipboard's contents. the promise is rejected if permission to access the clipboard is not granted. example after using navigator.permissions.query() to find out if we have (or if the user will be prompted to allow) "clipboa...
Clipboard.readText() - Web APIs
syntax var promise = navigator.clipboard.readtext() parameters none. return value a promise that resolves with a domstring containing the textual contents of the clipboard. ...
Clipboard - Web APIs
Web › API › Clipboard
s, you can request the clipboardread and clipboardwrite permissions to be able to use clipboard.readtext() and clipboard.writetext(). content scripts applied on http sites do not have access to the clipboard object. see extensions in firefox 63. in addition, read() and write() are disabled by default and require changing a preference to enable them. check the compatibility tables for each method before using it. specifications specification status comment clipboard api and eventsthe definition of 'clipboard' in that specification. working draft initial definition. ...
ClipboardItem.types - Web APIs
the read-only types property of the clipboarditem interface returns an array of mime types available within the clipboarditem syntax var types = clipboarditem.types; value an array of available mime types. examples in the below example, we're returning all items on the clipboard via the clipboard.read() method. then checking the types property for available types before utilizing the clipboarditem.gettype() method to return the blob object. if no clipboards contents is found for the specified type, an error is returned. async function getclipboardcontents() { try { const clipboarditems = await navigator.clipboard.read(); for (const clipboarditem of clipboarditems) { for (const type of clipboarditem.types) { const blob = await clipboarditem.gettype(type...
CloseEvent.initCloseEvent() - Web APIs
once dispatched, it doesn't do anything anymore. do not use this method anymore as it is deprecated. ...
console - Web APIs
Web › API › Console
led me 2 times. [13:14:13.485] hello, bob. you've called me 3 times. [13:14:13.487] hello, bob. you've called me 4 times. [13:14:13.488] hello, bob. you've called me 5 times. styling console output you can use the %c directive to apply a css style to console output: console.log("this is %cmy stylish message", "color: yellow; font-style: italic; background-color: blue;padding: 2px"); the text before the directive will not be affected, but the text after the directive will be styled using the css declarations in the parameter. the properties usable along with the %c syntax are as follows (at least, in firefox — they may differ in other browsers): background and its longhand equivalents. border and its longhand equivalents border-radius box-decoration-break box-shadow clear and fl...
Constraint validation API - Web APIs
concepts and usage certain html form controls, such as <input>, <select> and <textarea>, can restrict the format of allowable values, using attributes like required and pattern to set basic constraints. 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. note: client-side constraint validation doesn't remove the need for validation on the server side. ...
ConvolverNode.normalize - Web APIs
working draft ...
CountQueuingStrategy.CountQueuingStrategy() - Web APIs
the countqueuingstrategy() constructor creates and returns a countqueuingstrategy object instance. syntax var countqueuingstrategy = new countqueuingstrategy({highwatermark}); parameters {highwatermark} an object containing a highwatermark property. this is a non-negative integer defining the total number of chunks that can be contained in the internal queue before backpressure is applied. return value an instance of the countqueuingstrategy object. exceptions none. examples const queuingstrategy = new countqueuingstrategy({ highwatermark: 1 }); const writablestream = new writablestream({ // implement the sink write(chunk) { ... }, close() { ... }, abort(err) { console.log("sink error:", err); } }, queuingstrategy); var size = queuingstrategy.size();...
CustomElementRegistry.upgrade() - Web APIs
syntax customelements.upgrade(root); parameters root a node instance with shadow-containing descendant elements that are to be upgraded. if there are no descendant elements that can be upgraded, no error is thrown. return value void. ...
CustomElementRegistry - Web APIs
custom elements and querying registered elements. to get an instance of it, use the window.customelements property. methods customelementregistry.define() defines a new custom element. customelementregistry.get() returns the constuctor for the named custom element, or undefined if the custom element is not defined. customelementregistry.upgrade() upgrades a custom element directly, even before it is connected to its shadow root. customelementregistry.whendefined() returns an empty promise that resolves when a custom element becomes defined with the given name. if such a custom element is already defined, the returned promise is immediately fulfilled. examples the following code is taken from our word-count-web-component example (see it live also). note how we use the customelement...
CustomEvent.initCustomEvent() - Web APIs
once dispatched, it doesn't do anything anymore. do not use this method anymore, as it is deprecated. ...
DOMImplementation.createDocumentType() - Web APIs
syntax var doctype = document.implementation.createdocumenttype(qualifiednamestr, publicid, systemid); parameters qualifiednamestr is a domstring containing the qualified name, like svg:svg. publicid is a domstring containing the public identifier. ...
DirectoryReaderSync - Web APIs
ies in a directory. this interface has been abandonned: it was on a standard track and it proves not a good idea. do not use it anymore. about this document this document was last updated on march 2, 2012 and follows the w3c specifications (working draft) drafted on april 19, 2011. this specification is pretty much abandoned, having failed to reach any substantial traction. basic concepts before you call the only method in this interface, readentries(), create the directoryentrysync object. but directoryentrysync (as well as fileentrysync) is not a data type that you can pass between a calling app and web worker thread. it's not a big deal, because you don't really need to have the main app and the worker thread see the same javascript object; you just need them to access the same files.
Document: DOMContentLoaded event - Web APIs
aying domcontentloaded <script> document.addeventlistener('domcontentloaded', (event) => { console.log('dom fully loaded and parsed'); }); for( let i = 0; i < 1000000000; i++) {} // this synchronous script is going to delay parsing of the dom, // so the domcontentloaded event is going to launch later. </script> checking whether loading is already complete domcontentloaded may fire before your script has a chance to run, so it is wise to check before adding a listener. function dosomething() { console.info('dom loaded'); } if (document.readystate === 'loading') { // loading hasn't finished yet document.addeventlistener('domcontentloaded', dosomething); } else { // `domcontentloaded` has already fired dosomething(); } live example html <div class="controls"> <button...
Document.adoptNode() - Web APIs
ject. 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 iframeimages = iframe.contentdocument.queryselectorall('img'); const newparent = document.getelementbyid('images'); iframeimages.foreach(function(imgel) { newparent.appendchild(document.adoptnode(imgel)); }); notes before they can be inserted into the current document, nodes from external documents should either be: cloned using document.importnode(); or adopted using document.adoptnode(). best practice: although firefox doesn't currently enforce this rule, we encourage you to follow this rule for improved future compatibility. for more on the node.ownerdocument issues, see the w3c dom faq. specification...
Document: animationend event - Web APIs
bubbles yes cancelable no interface animationevent event handler property onanimationend the original target for this event is the element that had the animation applied. you can listen for this event on the document interface to handle it in the capture or bubbling phases. for full details on this event please see the page on htmlelement: animationend. ...
Document.caretRangeFromPoint() - Web APIs
offset = range.offset; } else if (document.caretrangefrompoint) { range = document.caretrangefrompoint(e.clientx, e.clienty); textnode = range.startcontainer; offset = range.startoffset; } // only split text_nodes if (textnode && textnode.nodetype == 3) { let replacement = textnode.splittext(offset); let br = document.createelement('br'); textnode.parentnode.insertbefore(br, replacement); } } let paragraphs = document.getelementsbytagname("p"); for (let i = 0; i < paragraphs.length; i++) { paragraphs[i].addeventlistener('click', insertbreakatpoint, false); } result ...
Document.cookie - Web APIs
Web › API › Document › cookie
s a concern, it's important that any web app implementation invalidate cookie data after a certain timeout instead of relying on the browser to do it. many browsers let users specify that cookies should never expire, which is not necessarily safe. see date.toutcstring() for help formatting this value. ;secure cookie to only be transmitted over secure protocol as https. before chrome 52, this flag could appear with cookies from http domains. ;samesite samesite prevents the browser from sending this cookie along with cross-site requests. possible values are lax, strict 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...
Document.createRange() - Web APIs
the document.createrange() method returns a new range object. syntax range = document.createrange(); range is the created range object. example let range = document.createrange(); range.setstart(startnode, startoffset); range.setend(endnode, endoffset); notes once a range is created, you need to set its boundary points before you can make use of most of its methods. specifications specification status comment domthe definition of 'document.createrange' in that specification. living standard ...
Document.createTouch() - Web APIs
the document.createtouch() method creates and returns a new touch object. syntax var touch = documenttouch.createtouch(view, target, identifier, pagex, pagey, screenx, screeny); parameters note: all parameters are optional. view the window in which the touch occurred. target the eventtarget for the touch. identifier the value for touch.identifier. pagex the value for touch.pagex. pagey the value for touch.pagey. screenx the value for touch.screenx. screeny the value for touch.screeny. note: previous versions of this method included the following additional parameters but those parameters are not included in either of the standards listed below. ...
Document.createTouchList() - Web APIs
the document.createtouchlist() method creates and returns a new touchlist object. syntax var list = documenttouch.createtouchlist([touch1 [, touch2 [, ...]]]); parameters touches zero or more touch objects. note: firefox also accepts an array of touch objects. return value list a touchlist object containing the touch objects specified by the touches parameter. example this example illustrates using the document.createtouchlist() method to create touchlist objects. in following code snippet, some touch objects are created for the target element and those touch points are then used to create some touchlist objects. ...
Document.execCommand() - Web APIs
affect an entire line (indenting). when using contenteditable, execcommand() affects the currently active editable element. syntax document.execcommand(acommandname, ashowdefaultui, avalueargument) return value a boolean that is false if the command is unsupported or disabled. note: only returns true if part of a user interaction. don't try using the return value to verify browser support before calling a command. parameters acommandname a domstring specifying the name of the command to execute. see commands for a list of possible commands. ashowdefaultui a boolean indicating whether the default user interface should be shown. this is not implemented in mozilla. avalueargument for commands which require an input argument, is a domstring providing that information. for example, ...
Document.fullscreenEnabled - Web APIs
if it is modified (even in strict mode); the setter is a no-operation and it will be ignored. syntax var isfullscreenavailable = document.fullscreenenabled; value a boolean value which is true if the document and the elements within can be placed into full-screen mode by calling element.requestfullscreen(). if full-screen mode isn't available, this value is false. example in this example, before attempting to request full-screen mode for a <video> element, the value of fullscreenenabled is checked, in order to avoid making the attempt when not available. function requestfullscreen() { if (document.fullscreenenabled) { videoelement.requestfullscreen(); } else { console.log('your browser cannot use fullscreen right now'); } } specifications specification status...
Document.getElementById() - Web APIs
ns null. note that the id parameter is case-sensitive, so document.getelementbyid("main") will return null instead of the element <div id="main"> because "m" and "m" are different for the purposes of this method. elements not in the document are not searched by getelementbyid(). when creating an element and assigning it an id, you have to insert the element into the document tree with node.insertbefore() or a similar method before you can access it with getelementbyid(): var element = document.createelement('div'); element.id = 'testqq'; var el = document.getelementbyid('testqq'); // el will be null! non-html documents. the dom implementation must have information that says which attributes are of type id. attributes with the name "id" are not of type id unless so defined in the document's d...
Document.getElementsByTagName() - Web APIs
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 status comment domthe...
Document.getElementsByTagNameNS() - Web APIs
hod returns a htmlcollection both in gecko and internet explorer. opera returns a nodelist, but with a nameditem method implemented, which makes it similar to a htmlcollection. as of january 2012, only in webkit browsers is the returned value a pure nodelist. see bug 14869 for details. note: currently parameters in this method are case-sensitive, but they were case-insensitive in firefox 3.5 and before. see the note in browser compatibility section in element.getelementsbytagnamens for details. example in the following example getelementsbytagnamens starts from a particular parent element, and searches topdown recursively through the dom from that parent element, looking for child elements matching the tag name parameter. note that when the node on which getelementsbytagname is invoked is no...
Document: keypress event - Web APIs
the keypress event is fired when a key that produces a character value is pressed down. examples of keys that produce a character value are alphabetic, numeric, and punctuation keys. examples of keys that don't produce a character value are modifier keys such as alt, shift, ctrl, or meta. since this event has been deprecated, you should look to use beforeinput or keydown instead. interface keyboardevent bubbles yes cancelable yes default action varies: keypress event; launch text composition system; blur and focus events; domactivate event; other event examples addeventlistener keypress example this example logs the keyboardevent.code value whenever you press a key. <p>press inside this iframe first to focus it, then try pressi...
Document.onfullscreenchange - Web APIs
syntax targetdocument.onfullscreenchange = fullscreenchangehandler; value an event handler which is invoked whenever the document receives a fullscreenchange event, indicating that the document is transitioning into or out of full-screen mode. usage notes the fullscreenchange event does not directly specify whether the transition is into or out of full-screen mode, so your event handler should look at the value of document.fullscreenelement. ...
Document.open() - Web APIs
Web › API › Document › open
example: all event listeners currently registered on the document, nodes inside the document, or the document's window are removed. all existing nodes are removed from the document. syntax document.open(); parameters none. return value a document object instance. examples the following simple code opens the document and replaces its content with a number of different html fragments, before closing it again. document.open(); document.write("<p>hello world!</p>"); document.write("<p>i am a fish</p>"); document.write("<p>the number is 42</p>"); document.close(); notes an automatic document.open() call happens when document.write() is called after the page has loaded. for years firefox and internet explorer additionally erased all javascript variables, etc., in addition to removin...
Document.popupNode - Web APIs
ly, this property will be checked during a popupshowing event handler for a context menu to initialize the menu based on the context. this property is only set for popups attached via the popup or context attributes. for other types of popups, the value is not changed. in these other cases, for example when calling the popup's showpopup method, you may wish to set the popupnode property directly beforehand. this property applies only to xul documents. syntax var node = document.popupnode; example <menupopup id="toolbarcontextmenu"> ... <menuitem oncommand="mailnewscore.deletebutton(document.popupnode)"> ... </menupopup> ...
Document.readyState - Web APIs
living standar...
Document.title - Web APIs
Web › API › Document › title
"; alert(document.title); // displays "goodbye world!" </script> </body> </html> notes this property applies to html, svg, xul, and other documents in gecko. for html documents the initial value of document.title is the text content of the <title> element. for xul it's the value of the title attribute of the <xul:window> or other top-level xul element. in xul, accessing document.title before the document is fully loaded has undefined behavior: document.title may return an empty string and setting document.title may have no effect. specifications specification status comment html living standardthe definition of 'document.title' in that specification. living standard ...
Document: transitionend event - Web APIs
bubbles yes cancelable yes interface transitionevent event handler property ontransitionend the transitionend event is fired in both directions - as it finishes transitioning to the transitioned state, and when it fully reverts to the default or non-transitioned state. ...
Document: transitionrun event - Web APIs
bubbles yes cancelable no interface transitionevent event handler property ontransitionrun the original target for this event is the element that had the transition applied. you can listen for this event on the document interface to handle it in the capture or bubbling phases. for full details on this event please see the page on htmlelement: transitionrun. ...
Document - Web APIs
Web › API › Document
inter is locked. null if lock is pending, pointer is unlocked, or if the target is in another document. documentorshadowroot.stylesheetsread only returns a stylesheetlist of cssstylesheet objects for stylesheets explicitly linked into, or embedded in a document. event handlers document.onafterscriptexecute represents the event handling code for the afterscriptexecute event. document.onbeforescriptexecute represents the event handling code for the beforescriptexecute event. document.oncopy represents the event handling code for the copy event. document.oncut represents the event handling code for the cut event. document.onfullscreenchange is an eventhandler representing the code to be called when the fullscreenchange event is raised. document.onfullscreenerror is an eve...
DocumentFragment - Web APIs
fragment.getelementbyid() returns the first element node within the documentfragment, in document order, that matches the specified id. functionally equivalent to document.getelementbyid(). usage notes a common use for documentfragment is to create one, assemble a dom subtree within it, then append or insert the fragment into the dom using node interface methods such as appendchild() or insertbefore(). doing this moves the fragment's nodes into the dom, leaving behind an empty documentfragment. because all of the nodes are inserted into the document at once, only one reflow and render is triggered instead of potentially one for each node inserted if they were inserted separately. this interface is also of great use with web components: <template> elements contain a documentfragment in their...
DocumentOrShadowRoot.caretPositionFromPoint() - Web APIs
etnode; offset = range.offset; } else if (document.caretrangefrompoint) { range = document.caretrangefrompoint(e.clientx, e.clienty); textnode = range.startcontainer; offset = range.startoffset; } // only split text_nodes if (textnode.nodetype == 3) { var replacement = textnode.splittext(offset); var br = document.createelement('br'); textnode.parentnode.insertbefore(br, replacement); } } window.onload = function (){ var paragraphs = document.getelementsbytagname("p"); for (i=0 ; i < paragraphs.length; i++) { paragraphs[i].addeventlistener("click", insertbreakatpoint, false); } }; specifications specification status comment css object model (cssom) view modulethe definition of 'caretpositionfrompoint()' in that specifica...
Traversing an HTML table with JavaScript and DOM Interfaces - Web APIs
node object inside the document tree. createtextnode() and appendchild() is a simple way to include white space between the words hello and world. another important note is that the appendchild method will append the child after the last child, just like the word world has been added after the word hello. so if you want to append a text node between hello and world, you will need to use insertbefore instead of appendchild. creating new elements with the document object and the createelement(..) method you can create new html elements or any other element you want with createelement. for 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.create...
EXT_float_blend - Web APIs
r drawelements() with blending enabled and a draw buffer with 32-bit floating-point components will no longer result in an invalid_operation error. usage notes on devices that support the ext_float_blend extension, it is automatically, implicitly, enabled when any one or more of ext_color_buffer_float, oes_texture_float, or webgl_color_buffer_float are enabled. this ensures that content written before ext_float_blend was exposed by webgl will function as expected. examples const gl = canvas.getcontext('webgl2'); // enable necessary extensions gl.getextension('ext_color_buffer_float'); gl.getextension('ext_float_blend'); const tex = gl.createtexture(); gl.bindtexture(gl.texture_2d, tex); // use floating point format gl.teximage2d(gl.texture_2d, 0, gl.rgba32f, 1, 1, 0, gl.rgba, gl.float, nu...
Element: click event - Web APIs
element receives a click event when a pointing device button (such as a mouse's primary mouse button) is both pressed and released while the pointer is located inside the element. bubbles yes cancelable yes interface mouseevent event handler property onclick if the button is pressed on one element and the pointer is moved outside the element before the button is released, the event is fired on the most specific ancestor element that contained both elements. click fires after both the mousedown and mouseup events have fired, in that order. usage notes the mouseevent object passed into the event handler for click has its detail property set to the number of times the target was clicked. in other words, detail will be 2 for a double-click, ...
Element.getAnimations() - Web APIs
udo-elements attached to element or one of its descendents. defaults to false. return value an array of animation objects, each representing an animation currently targetting the element on which this method is called, or one of its descendant elements if { subtree: true } is specified. examples the following code snippet will wait for all animations on elem and its descendants to finish before removing the element from the document. promise.all( elem.getanimations({ subtree: true }) .map(animation => animation.finished) ).then(() => elem.remove()); specifications specification status comment web animationsthe definition of 'animatable.getanimations()' in that specification. working draft editor's draft. ...
Element.getAttribute() - Web APIs
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 the current dom specification draft specifies. the old dom 3 core specification, on the other hand, says that the correct retur...
Element.getAttributeNode() - Web APIs
etattributenode(attrname); attrnode is an attr node for the attribute. attrname is a string containing the name of the attribute. example // html: <div id="top" /> let t = document.getelementbyid("top"); let idattr = t.getattributenode("id"); alert(idattr.value == "top") notes when called on an html element in a dom flagged as an html document, getattributenode lower-cases its argument before proceeding. the attr node inherits from node, but is not considered a part of the document tree. common node attributes like parentnode, previoussibling, and nextsibling are null for an attr node. you can, however, get the element to which the attribute belongs with the ownerelement property. getattribute is usually used instead of getattributenode to get the value of an element's attribute. d...
Element.getElementsByTagName() - Web APIs
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 of the specified element. s...
Element.hasAttributeNS() - Web APIs
hasattributens returns a boolean value indicating whether the current element has the specified attribute. syntax result = element.hasattributens(namespace,localname) result is the boolean value true or false. namespace is a string specifying the namespace of the attribute. localname is the name of the attribute. ...
Element: keypress event - Web APIs
the keypress event is fired when a key that produces a character value is pressed down. examples of keys that produce a character value are alphabetic, numeric, and punctuation keys. examples of keys that don't produce a character value are modifier keys such as alt, shift, ctrl, or meta. since this event has been deprecated, you should look to use beforeinput or keydown instead. interface keyboardevent bubbles yes cancelable yes default action varies: keypress event; launch text composition system; blur and focus events; domactivate event; other event examples addeventlistener keypress example this example logs the keyboardevent.code value whenever you press a key after focussing the <input> element. <div> <label for="sample...
Element.namespaceURI - Web APIs
syntax namespace = element.namespaceuri example in this snippet, an element is being examined for its localname and its namespaceuri. if the namespaceuri returns the xul namespace and the localname returns "browser", then the node is understood to be a xul <browser/>. ...
Element.prefix - Web APIs
Web › API › Element › prefix
syntax string = element.prefix examples the following logs "x" to the console. <x:div onclick="console.log(this.prefix)"/> notes this will only work when a namespace-aware parser is used, i.e. when a document is served with an xml mime type. this will not work for html documents. ...
Element.scrollWidth - Web APIs
screen due to overflow. 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. if the element's content can fit without a need for horizontal 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. example <!doctype html> <html> <head...
Element: webkitmouseforcechanged event - Web APIs
echanged event is fired by safari each time the amount of pressure changes on the trackpad/touchscreen. bubbles unknown cancelable unknown interface mouseevent webkitmouseforcechanged is a proprietary, webkit-specific event introduced by apple to support their force touch events feature. this event first fires after the mousedown event and stops firing before the mouseup event. specifications not part of any specification. apple has a description at the mac developer library. ...
Element: webkitmouseforcewillbegin event - Web APIs
this offers the opportunity to tell the system not to trigger any default force touch actions if and when the click turns into a force touch event. to instruct macos not to engage any default force touch actions if the user apply enough pressure to activate a force touch event, call preventdefault() on the webkitmouseforcewillbegin event object. bubbles unknown cancelable unknown interface mouseevent webkitmouseforcewillbegin is a proprietary, webkit-specific event. it is part of the force touch events feature. ...
Element - Web APIs
Web › API › Element
ver property. mouseup fired when a pointing device button is released on an element. also available via the onmouseup property. webkitmouseforcechanged fired each time the amount of pressure changes on the trackpadtouchscreen. webkitmouseforcedown fired after the mousedown event as soon as sufficient pressure has been applied to qualify as a "force click". webkitmouseforcewillbegin fired before the mousedown event. webkitmouseforceup fired after the webkitmouseforcedown event as soon as the pressure has been reduced sufficiently to end the "force click". touch events touchcancel fired when one or more touch points have been disrupted in an implementation-specific manner (for example, too many touch points are created). also available via the ontouchcancel property. touchend f...
Event.cancelBubble - Web APIs
in later implementations, setting this to false does nothing. see browser compatibility for details. syntax event.cancelbubble = bool; var bool = event.cancelbubble; value a boolean. ...
Event.cancelable - Web APIs
Web › API › Event › cancelable
the cancelable read-only property of the event interface indicates whether the event can be canceled, and therefore prevented as if the event never happened. if the event is not cancelable, then its cancelable property will be false and the event listener cannot stop the event from occurring. event listeners that handle multiple kinds of events may want to check cancelable before invoking their preventdefault() methods. most browser-native events that can be canceled are the ones that result from the user interacting with the page. canceling the click, scroll, or beforeunload events would prevent the user from clicking on something, scrolling the page, or navigating away from the page, respectively. custom events created by other javascript code control if they can be canceled when they are ...
Event.explicitOriginalTarget - Web APIs
for example, mouse events are retargeted to their parent node when they happen over text nodes (see bug 185889), and in that case currenttarget will show the parent and explicitoriginaltarget will show the text node. explicitoriginaltarget differs from originaltarget in that it will never contain anonymous content. ...
Event.originalTarget - Web APIs
(mozilla-specific) in presence of xbl anonymous content this will be the anonymous node the event originally fired on. see anonymous content#event_flow_and_targeting for more details. note: originaltarget may also be native anonymous content (see bug 208427), in which case it's useless for non-privileged code. see also comparison of event targets example need an example that makes sense here specification this is a mozilla-specific property. ...
Event.preventDefault() - Web APIs
you can ...
EventTarget.removeEventListener() - Web APIs
hich specifies the type of event for which to remove an event listener. listener the eventlistener function of the event handler to remove from the event target. options optional an options object that specifies characteristics about the event listener. the available options are: capture: a boolean which indicates that events of this type will be dispatched to the registered listener before being dispatched to any eventtarget beneath it in the dom tree. mozsystemgroup: available only in code running in xbl or in firefox' chrome, it is a boolean defining if the listener is added to the system group. usecapture optional specifies whether the eventlistener to be removed is registered as a capturing listener or not. if this parameter is absent, a default value of false is assu...
FetchEvent.replacesClientId - Web APIs
o page b replacesclientid is the id of the client associated with page a. it can be an empty string when navigating from about:blank to another page, as about:blank's client will be reused, rather than be replaced. additionally, if the fetch isn't a navigation, replacesclientid will be an empty string. this could be used to access/communicate with a client that will imminently be replaced, right before a navigation. syntax var myreplacedclientid = fetchevent.replacesclientid; value a domstring. example self.addeventlistener('fetch', function(event) { console.log(event.replacesclientid); }); specifications specification status comment service workersthe definition of 'replacesclientid' in that specification. working draft initial definition. ...
FileReader.readAsDataURL() - Web APIs
for a full compatibility code you can see our crossbrowser possible solution for image preview. see also this more powerful example. specifications specification status comment file apithe definition of 'readasdataurl()' in that specification. working draft initial definition ...
FileSystemEntry.remove() - Web APIs
to recursively remove a directory as well as all of its contents and its subdirectories, call filesystemdirectoryentry.removerecursively() instead. syntax filesystementry.remove(successcallback[, errorcallback]); parameters successcallback a function which is called once the file has been successfully removed. errorcallback optional an optional callback which is called if the attempt to remove the file fails. return value undefined. ...
FileSystemEntry.toURL() - Web APIs
an image file named awesomesauce.jpg, the url returned by tourl() might be (depending on the browser's implementation) something like "filesystem:http://my-awesome-website.woot/temporary/awesomesauce.jpg". code that makes use of this might look like this: let img = document.createelement("img"); img.src = imagefileentry.tourl(); document.body.appendchild(img); assuming the scenario mentioned before the code, the result would be html that looks like this being appended to the end of the document: <img src="filesystem:http://my-awesome-website.woot/temporary/awesomesauce.jpg"> browser compatibility the compatibility table on this page is generated from structured data. if you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull re...
FileHandle API - Web APIs
ive, all operations of this lockedfile are guaranteed to happen sequentially on the underlying file without being interleaved with operations from other lockedfile. secured write operation for performance reasons, write (and read) operations are done in memory. periodically, the results of those operation are asynchronously flushed to the device storage area. if for some reason a problem occurs before that, you can lose the results of some operations. to avoid that problem, you can force the data to be flushed by using the lockedfile.flush() method. once this method has been successfully called, you can be sure your change on the file will be safe. // get a lockedfile object from the handle var myfile = myfilehandle.open('readwrite'); // start a writing operation var writing = myfile.append(...
File and Directory Entries API support in Firefox - Web APIs
sing a sandboxed virtual file system on the user's storage device. work to standardize the specification was abandoned back in 2012, but by that point, google chrome included its own implementation of the api. over time, a number of popular sites and web applications came to use it, often without providing any means of falling back to standard apis or even checking to be sure the api is available before using it. mozilla instead opted to implement other apis which can be used to solve many of the same problems, such as indexeddb; see the blog post why no filesystem api in firefox? for more insights. this has caused a number of popular web sites not to work properly on browsers other than chrome. because of that, an attempt was made to create a spec offering the features of google's api which co...
Introduction to the File and Directory Entries API - Web APIs
can access partially downloaded files (so that you can watch the first chapter of your dvd, even if the app is still downloading the rest of the content or if the app didn't complete the download because you had to run to catch a train). offline web mail client the client downloads attachments and stores them locally. the client caches attachments for later upload. ...
Using FormData Objects - Web APIs
sending files using a formdata object you can also send files using formdata. simply include an <input> element of type file in your <form>: <form enctype="multipart/form-data" method="post" name="fileinfo"> <label>your email address:</label> <input type="email" autocomplete="on" autofocus name="useri...
FormData.has() - Web APIs
Web › API › FormData › has
tain 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. example the following line creates an empty formdata object: var formdata = new formdata(); the following snippet shows the results of testing for the existence of username in the formdata object, before and after appending a username value to it with formdata.append: formdata.has('username'); // returns false formdata.append('username', 'chris'); formdata.has('username'); // returns true specifications specification status comment xmlhttprequestthe definition of 'has()' in that specification. living standard ...
Guide to the Fullscreen API - Web APIs
hod. let's consider this <video> element: <video controls id="myvideo"> <source src="somevideo.webm"></source> <source src="somevideo.mp4"></source> </video> we can put that video into full-screen mode as follows: var elem = document.getelementbyid("myvideo"); if (elem.requestfullscreen) { elem.requestfullscreen(); } this code checks for the existence of the requestfullscreen() method before calling it. presentation differences it's worth noting a key difference here between the gecko and webkit implementations at this time: gecko automatically adds css rules to the element to stretch it to fill the screen: "width: 100%; height: 100%". webkit doesn't do this; instead, it centers the fullscreen element at the same size in a screen that's otherwise black. to get the same fullscreen b...
GainNode - Web APIs
Web › API › GainNode
a gainnode always has exactly one input and one output, both with the same number of channels. the gain is a unitless value, changing with time, that is multiplied to each corresponding sample of all input channels. if modified, the new gain is instantly applied, causing unaesthetic 'clicks' in the resulting audio. to prevent this from happening, never change the value directly but use the exponential interpolation methods on the audioparam interface. ...
Geolocation.getCurrentPosition() - Web APIs
ion that takes a geolocationposition object as its sole input parameter. error optional an optional callback function that takes a geolocationpositionerror object as its sole input parameter. options optional an optional positionoptions object. options includes: maximumage: integer (milliseconds) | infinity - maximum cached position age. timeout: integer (milliseconds) - amount of time before the error callback is invoked, if 0 it will never invoke. enablehighaccuracy: false | true examples var options = { enablehighaccuracy: true, timeout: 5000, maximumage: 0 }; function success(pos) { var crd = pos.coords; console.log('your current position is:'); console.log(`latitude : ${crd.latitude}`); console.log(`longitude: ${crd.longitude}`); console.log(`more or le...
GeolocationPositionError.code - Web APIs
e acquisition of the geolocation information failed because the page didn't have the permission to do it. 2 position_unavailable the acquisition of the geolocation failed because one or several internal sources of position returned an internal error. 3 timeout the time allowed to acquire the geolocation, defined by positionoptions.timeout information that was reached before the information was obtained. specifications specification status comment geolocation apithe definition of 'positionerror.code' in that specification. recommendation initial definition ...
GeolocationPositionError - Web APIs
acquisition of the geolocation information failed because the page didn't have the permission to do it. 2 position_unavailable the acquisition of the geolocation failed because at least one internal source of position returned an internal error. 3 timeout the time allowed to acquire the geolocation, defined by positionoptions.timeout information was reached before the information was obtained. geolocationpositionerror.message read only secure context returns a human-readable domstring describing the details of the error. specifications note that this is primarily intended for debugging use and not to be shown directly in a user interface. methods the geolocationpositionerror interface neither implements nor inherits any method. specificat...
Using the Geolocation API - Web APIs
nd an optional positionoptions object. this object allows you to specify whether to enable high accuracy, a maximum age for the returned position value (up until this age it will be cached and reused if the same position is requested again; after this the browser will request fresh position data), and a timeout value that dictates how long the browser should attempt to get the position data for, before it times out. a call to watchposition could look like: function success(position) { dosomething(position.coords.latitude, position.coords.longitude); } function error() { alert('sorry, no position available.'); } const options = { enablehighaccuracy: true, maximumage: 30000, timeout: 27000 }; const watchid = navigator.geolocation.watchposition(success, error, options); describing ...
GlobalEventHandlers.onanimationcancel - Web APIs
ox to the bottom-right corner. @keyframes slidebox { from { left:0; top:0; } to { left:calc(100% - var(--boxwidth)); top:calc(100% - var(--boxwidth)) } } since the animation is described as taking place an infinite number of times, alternating direction each time, the box will glide back and forth between the two corners until stopped or the page is closed. javascript before we get to the animation code, we define a function which logs information to a box on the user's screen. we'll use this to show information about the events we receive. note the use of animationevent.animationname and animationevent.elapsedtime to get information about the event which occurred. function log(msg, event) { let logbox = document.getelementbyid("log"); logbox.innerhtml += msg; ...
GlobalEventHandlers.onanimationend - Web APIs
ottom-right corner. .slideanimation { animation: 5s ease-in-out 0s 1 slidebox; } @keyframes slidebox { from { left:0; top:0; } to { left:calc(100% - var(--boxwidth)); top:calc(100% - var(--boxwidth)) } } since the css describes the animation but doesn't connect it to the box, we'll need some javascript code to do that. we'll get to that shortly. javascript content before we get to the animation code, we define a function which logs information to a box on the user's screen. we'll use this to show information about the events we receive. note the use of animationevent.animationname and animationevent.elapsedtime to get information about the event which occurred. function log(msg, event) { let logbox = document.getelementbyid("log"); logbox.innerhtml += msg; ...
GlobalEventHandlers.onanimationstart - Web APIs
ottom-right corner. .slideanimation { animation: 5s ease-in-out 0s 1 slidebox; } @keyframes slidebox { from { left:0; top:0; } to { left:calc(100% - var(--boxwidth)); top:calc(100% - var(--boxwidth)) } } since the css describes the animation but doesn't connect it to the box, we'll need some javascript code to do that. we'll get to that shortly. javascript content before we get to the animation code, we define a function which logs information to a box on the user's screen. we'll use this to show information about the events we receive. note the use of animationevent.animationname and animationevent.elapsedtime to get information about the event which occurred. function log(msg, event) { let logbox = document.getelementbyid("log"); logbox.innerhtml += msg; ...
GlobalEventHandlers.onclose - Web APIs
syntax target.onclose = functionref; value functionref is a function name or a function expression. the function receives an event object as its sole argument. only one onclose handler can be assigned to an object at a time. ...
GlobalEventHandlers.oninvalid - Web APIs
syntax target.oninvalid = functionref; var functionref = target.oninvalid; value functionref is a function name or a function expression. ...
GlobalEventHandlers.ontransitionend - Web APIs
one way this can happen is by changing the value of the transition-property attribute which applies to the target. another is if the display attribute is set to none. ...
GlobalEventHandlers - Web APIs
...
Audio() - Web APIs
of an audio file to be associated with the new audio element. return value a new htmlaudioelement object, configured to be used for playing back the audio from the file specified by url.the new object's preload property is set to auto and its src property is set to the specified url or null if no url is given. if a url is specified, the browser begins to asynchronously load the media resource before returning the new object. usage notes you can also use other element-creation methods, such as the document object's createelement() method, to construct a new htmlaudioelement. determining when playback can begin there are three ways you can tell when enough of the audio file has loaded to allow playback to begin: check the value of the readystate property. if it's htmlmediaelement.hav...
msAudioCategory - Web APIs
specific to internet explorer and microsoft edge. msaudiocategory specifies the purpose of the audio or video media, such as background audio or alerts. syntax <audio controls="controls" msaudiocategory="backgroundcapablemedia"> </audio> the msaudiocategory property offers a variety of values that can enhance the behavior of your audio-aware app. note that you must set the msaudiocategory before setting the src property in code. value include a description of the property's value, including 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 backgroundcapab...
HTMLCanvasElement.toDataURL() - Web APIs
living standard no change since the latest snapshot, html5 html 5.1the definition of 'htmlcanvaselement.todataurl' in that specification. recommendation html5the definition of 'ht...
HTMLCanvasElement: webglcontextrestored event - Web APIs
you need to reinitialize the state of your webgl application and recreate resources. ...
HTMLCollection - Web APIs
an htmlcollection in the html dom is live; it is automatically updated when the underlying document is changed. ...
HTMLElement: animationend event - Web APIs
the animationend event is fired when a css animation has completed. if the animation aborts before reaching completion, such as if the element is removed from the dom or the animation is removed from the element, the animationend event is not fired. bubbles yes cancelable no interface animationevent event handler property onanimationend examples this example gets an element that's being animated and listens for the animationend event: const animated = document.queryselector('.animated'); animated.addeventlistener('animationend', () => { console.log('animation ended'); }); the same, but using the onanimationend event handler property: const animated = document.queryselector('.animated'); animated.onanimationend = () => { console.l...
HTMLElement.offsetHeight - Web APIs
the htmlelement.offsetheight read-only property returns the height of an element, including vertical padding and borders, as an integer. typically, offsetheight is a measurement in pixels of the element's css height, including any borders, padding, and horizontal scrollbars (if rendered). it does not include the height of pseudo-elements such as ::before or ::after. for the document body object, the measurement includes total linear content height instead of the element's css height. floated elements extending below other linear content are ignored. if the element is hidden (for example, by setting style.display on the element or one of its ancestors to "none"), then 0 is returned. this property will round the value to an integer. if you need a fractional value, use element.getboundingclien...
HTMLElement.offsetWidth - Web APIs
if the element is hidden (for example, by setting style.display on the element or one of its ancestors to "none"), then 0 is returned. ...
HTMLElement - Web APIs
vailable via the onanimationcancel property. animationend fired when an animation has completed normally. also available via the onanimationend property. animationiteration fired when an animation iteration has completed. also available via the onanimationiteration property. animationstart fired when an animation starts. also available via the onanimationstart property. input events beforeinput fired when the value of an <input>, <select>, or <textarea> element is about to be modified. input fired when the value of an <input>, <select>, or <textarea> element has been changed. also available via the oninput property. change fired when the value of an <input>, <select>, or <textarea> element has been changed and committed by the user. unlike the input event, the change event is...
HTMLFrameSetElement - Web APIs
de a frameset. methods no specific method; inherits methods from its parent, htmlelement and from windoweventhandlers. event handlers no specific event handler; inherits event handlers from its parent, htmlelement and from windoweventhandlers. windoweventhandlers.onafterprint is an eventhandler representing the code to be called when the afterprint event is raised. windoweventhandlers.onbeforeprint is an eventhandler representing the code to be called when the beforeprint event is raised. windoweventhandlers.onbeforeunload is an eventhandler representing the code to be called when the beforeunload event is raised. windoweventhandlers.onhashchange is an eventhandler representing the code to be called when the hashchange event is raised. windoweventhandlers.onlanguagechange is a...
HTMLHyperlinkElementUtils.password - Web APIs
if it is set without first setting the username property, it silently fails. ...
HTMLHyperlinkElementUtils.username - Web APIs
the htmlhyperlinkelementutils.username property is a usvstring containing the username specified before the domain name. syntax string = object.username; object.username = string; examples // let's <a id="myanchor" href="https://anonymous:flabada@developer.mozilla.org/docs/htmlhyperlinkelementutils.username"> be in the document var anchor = document.getelementbyid("myanchor"); var result = anchor.username; // returns:'anonymous' specifications specification status comment html living standardthe definition of 'htmlhyperlinkelementutils.username' in that specification. living standard initial definition. ...
HTMLHyperlinkElementUtils - Web APIs
this is a usvstring containing an initial '/' followed by the path of the url. htmlhyperlinkelementutils.search this is a usvstring containing a '?' followed by the parameters of the url. htmlhyperlinkelementutils.hash this is a usvstring containing a '#' followed by the fragment identifier of the url. htmlhyperlinkelementutils.username this is a usvstring containing the username specified before the domain name. htmlhyperlinkelementutils.password this is a usvstring containing the password specified before the domain name. htmlhyperlinkelementutils.origin read only this returns a usvstring containing the origin of the url (that is its scheme, its domain and its port). methods note: this interface doesn't inherit any method. htmlhyperlinkelementutils.tostring() this returns ...
HTMLImageElement.alt - Web APIs
por et arcu.</p> </div> </div> css the css for this example simply sets up the styles for the layout as shown in the result below. they're not crucial to the concept shown in the html above, but you may expand the view below if you wish to read the css used. view the css editors: if you change the css below, please be sure to close the details box using the toggle at the top of the css view before saving. otherwise, readers will find it open by default, which is not the intent here. body { margin: 0; padding: 0; } p { margin-block-start: 0; margin-block-end: 1em; margin-top: 0; margin-bottom: 1em; } .container { width: 100vh; height: 95vh; font: 16px arial,helvetica,sans-serif; } .left-margin { background-color: rgb(241, 240, 237, 255); width: 9em; height: 100%;...
HTMLImageElement.complete - Web APIs
ading, such as a command that performs red-eye removal on the image in the lightbox. while ideally this command wouldn't even be executed if the image hasn't fully loaded, for improved reliability you want to check to ensure this is the case. so the fixredeyecommand() function, which is called by the button that triggers red-eye removal, checks the value of the lightbox image's complete property before attempting to do its work. this is demonstrated in the code below. let lightboxelem = document.queryselector("#lightbox"); let lightboximgelem = lightboxelem.queryselector("img"); let lightboxcontrolselem = lightboxelem.queryselector(".toolbar"); async function loadimage(url, elem) { return new promise((resolve, reject) => { elem.onload = () => resolve(elem); elem.onerror = reject; ...
HTMLImageElement.loading - Web APIs
formance. the possible values are: eager the default behavior, eager tells the browser to load the image as soon as the <img> element is processed. lazy tells the user agent to hold off on loading the image until the browser estimates that it will be needed imminently. for instance, if the user is scrolling through the document, a value of lazy will cause the image to only be loaded shortly before it will appear in the window's visual viewport. usage notes timing of the load event the load event is fired when the document has been fully processed. when images are loaded eagerly (which is the default), every image in the document must be fetched before the load event can fire. by specifying the value lazy for loading, you prevent the image from delaying the load attribute by the amount...
HTMLImageElement.naturalHeight - Web APIs
width} x ` + `${image.naturalheight} pixels<br>`; output.innerhtml += `displayed size: ${image.width} x ` + `${image.height} pixels`; }); the javascript code simply dumps the natural and as-displayed sizes into the <div> with the class output. this is done in response to the window's load event handler, in order to ensure that the image is available before attempting to examine its width and height. result specifications specification status comment html living standardthe definition of 'htmlimageelement.naturalheight' in that specification. living standard browser compatibility the compatibility table on this page is generated from structured data. if you'd like to contribute to the data, please chec...
HTMLImageElement.naturalWidth - Web APIs
width} x ` + `${image.naturalheight} pixels<br>`; output.innerhtml += `displayed size: ${image.width} x ` + `${image.height} pixels`; }); the javascript code simply dumps the natural and as-displayed sizes into the <div> with the class output. this is done in response to the window's load event handler, in order to ensure that the image is available before attempting to examine its width and height. result specifications specification status comment html living standardthe definition of 'htmlimageelement.naturalwidth' in that specification. living standard browser compatibility the compatibility table on this page is generated from structured data. if you'd like to contribute to the data, please check...
HTMLImageElement.srcset - Web APIs
ith a valid url referencing a non-interactive graphic resource. this is followed by a comma (,) character and then a condition descriptor that indicates the circumstances in which the indicated image should be used. space characters, other than the whitespace separating the url and the corresponding condition descriptor, are ignored; this includes both leading and trailing space, as well as space before or after each comma. if the condition descriptor is not provided (in other words, the image candidate provides 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 ...
HTMLInputElement: invalid event - Web APIs
y its constraints. bubbles no cancelable yes interface event event handler property globaleventhandlers.oninvalid this event can be useful for displaying a summary of the problems with a form on submission. when a form is submitted, invalid events are fired at each form control that is invalid. the validity of submittable elements is checked before submitting their owner <form>, or after the checkvalidity() method of the element or its owner <form> is called. it is not checked on blur. examples if a form is submitted with an invalid value, the submittable elements are checked and, if an error is found, the invalid event will fire on the invalid element. in this example, when an invalid event fires because of an invalid value in the input...
HTMLInputElement.setRangeText() - Web APIs
current selection). end optional the 0-based index of the character after the last character to replace. defaults to the current selectionend value (the end of the user's current selection). selectmode optional a string defining how the selection should be set after the text has been replaced. possible values: "select" selects the newly inserted text. "start"moves the selection to just before the inserted text. "end" moves the selection to just after the inserted text. "preserve" attempts to preserve the selection. this is the default. example click the button in this example to replace part of the text in the text box. the newly inserted text will be highlighted (selected) afterwards. html <input type="text" id="text-box" size="30" value="this text has not been updated."...
HTMLInputElement.stepDown() - Web APIs
lue given in the step attribute, multiplied by the parameter, within the constraints set within the form control. the default value for the parameter, if not is passed, is 1. the method will not cause the value to go below the min value set or defy the constraints set by the step attribute. a negative value for n will increment the value, but will not increment beyond the max value. if the value before invoking the stepdown() method is invalid, for example, if it doesn't match the constraints set by the step attribute, invoking the stepdown() method will return a value that does match the form controls constraints. if the form control is non time, date, or numeric in nature, and therefore does not support the step attribute (see the list of supported input types in the the table above), or if ...
HTMLInputElement.stepUp() - Web APIs
step="2" max="10"> 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 on the form control. the default value for the parameter, if no value is passed, is 1. the method will not cause the value to exceed the set max value, or defy the constraints set by the step attribute. if the value before invoking the stepup() method is invalid—for example, if it doesn't match the constraints set by the step attribute—invoking the stepup() method will return a value that does match the form controls constraints. if the form control is non time, date, or numeric in nature, and therefore does not support the step attribute (see the list of supported input types in the the table above), or if th...
HTMLInputElement - Web APIs
, unless the user overrides it, for example by typing in a different control. only one form element in a document can have the autofocus attribute. it cannot be applied if the type attribute is set to hidden (that is, you cannot automatically set focus to a hidden control). required boolean: returns / sets the element's required attribute, indicating that the user must fill in a value before submitting a form. value string: returns / sets the current value of the control. note: if the user enters a value different from the value expected, this may return an empty string. validity read only validitystate object: returns the element's current validity state. validationmessage read only string: returns a localized message that describes the v...
HTMLMediaElement.currentTime - Web APIs
the play() method is called. setting currenttime to a new value seeks the media to the given time, if the media is available. for media without a known duration—such as media being streamed live—it's possible that the browser may not be able to obtain parts of the media that have expired from the media buffer. also, media whose timeline doesn't begin at 0 seconds cannot be seeked to a time before its timeline's earliest time. the length of the media in seconds can be determined using the duration property. example var video = document.createelement('video'); console.log(video.currenttime); usage notes reduced time precision to offer protection against timing attacks and fingerprinting, browsers may round or otherwise adjust the value returned by currenttime. specifications ...
HTMLMediaElement.load() - Web APIs
appropriate media resource given the options specified in the <audio> or <video> element and its src attribute or child <source> element(s). this is described in more detail in supporting multiple formats in video and audio content. the process of aborting any ongoing activities will cause any outstanding promises returned by play() being resolved or rejected as appropriate based on their status before the loading of new media can begin. pending play promises are aborted with an "aborterror" domexception. appropriate events will be sent to the media element itself as the load process proceeds: if the element is already in the process of loading media, that load process is aborted and the abort event is sent. if the element has already been initialized with media, the emptied event is sent.
HTMLMediaElement.play() - Web APIs
ed 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 rejected. see the example below for more information. 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. for even more in-depth information about autoplay and autoplay blocking, see our article autoplay guide for media and web audio apis. example this example demonstrates how to confirm that playback has begun and how to gracefully handle blocked automatic playback: let videoelem = document.getelementbyid(...
HTMLMediaElement - Web APIs
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 double representing the number of samples per second that will be played. for example, 44100 samples per second is the sample rate used by cd audio. htmlmediaelement.muted is a boolean that determines whether audio is muted. true if the audio is muted and false otherw...
HTMLOrForeignElement.dataset - Web APIs
moved (including the dash); for any dash (u+002d) followed by an ascii lowercase letter a to z, the dash is removed, and the letter is transformed into its uppercase counterpart; other characters (including other dashes) are left unchanged. camelcase to dash-style conversion the opposite transformation, which maps a key to an attribute name, uses the following rules: restriction: before the transformation, a dash must not be immediately followed by an ascii lowercase letter a to z; the prefix data- is added; any ascii uppercase letter a to z is transformed into a dash, followed by its lowercase counterpart; other characters are left unchanged. the restriction in the rules above ensures that the two transformations are the inverse one of the other. for example, the a...
HTMLSelectElement - Web APIs
ng the name html attribute, containing the name of this control used by servers and dom search functions. htmlselectelement.optionsread only an htmloptionscollection representing the set of <option> (htmloptionelement) elements contained by this element. htmlselectelement.required a boolean reflecting the required html attribute, which indicates whether the user is required to select a value before submitting the form. htmlselectelement.selectedindex a long reflecting the index of the first selected <option> element. the value -1 indicates no element is selected. htmlselectelement.selectedoptionsread only an htmlcollection representing the set of <option> elements that are selected. htmlselectelement.size a long reflecting the size html attribute, which contains the number of visibl...
HTMLSpanElement - Web APIs
n that specification. living standard html 5.2the definition of 'htmlspanelement' in that specification. recommendation html 5.1the definition of 'htmlspanelement' in that specification. recommendation html5the definition of 'htmlspanelement' in that specification. recommendation initial definition, as <span> was associated with an htmlelement before that. ...
HTMLTableRowElement - Web APIs
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.insertcell() inserts a new cell just before the given position in the row. if the given position is not given or is -1, it appends the cell to 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 -1, it raises a domexception with the indexsizeerror value. returns a reference to a htmltablecellelement [en-us]. specifications specification status c...
HTMLTableSectionElement - Web APIs
". 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. htmltablesectionelement.insertrow() inserts a new row just before the given position in the section. if the given position is not given or is -1, it appends the row to the end of 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 -1, it raises a domexception with the indexsizeerror value. specifications specification status comment html living standardth...
HTMLTextAreaElement - Web APIs
r string: returns / sets the element's placeholder attribute, containing a hint to the user about what to enter in the control. readonly boolean: returns / sets the element's readonly attribute, indicating that the user cannot modify the value of the control. required boolean: returns / sets the element's required attribute, indicating that the user must specify a value before submitting the form. rows unsigned long: returns / sets the element's rows attribute, indicating the number of visible text lines for the control. selectiondirection string: returns / sets 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. thi...
The HTML DOM API - Web APIs
present individual draggable (or dragged) items, groups of dragged or draggable items, and to handle the drag and drop process. datatransfer datatransferitem datatransferitemlist dragevent page history interfaces the history api interfaces let you access information about the browser's history, as well as to shift the browser's current tab forward and backward through that history. beforeunloadevent hashchangeevent history location pagetransitionevent popstateevent web components interfaces these interfaces are used by the web components api to create and manage the available custom elements. customelementregistry miscellaneous and supporting interfaces these supporting object types are used in a variety of ways in the html dom api. in addition, promiserejectionev...
Recommended Drag Types - Web APIs
ny comments. for convenience, the special type url may be used to refer to the first valid link within data for the text/uri-list type. do not add data with the url type — attempting to do so will set the value of the text/uri-list type instead. var url = event.datatransfer.getdata("url"); you may also see data with the mozilla-specific type text/x-moz-url. if it appears, it should appear before the text/uri-list type. it holds the urls of links followed by their titles, separated by a linebreak. for example: http://www.mozilla.org mozilla http://www.example.com example dragging html and xml html content may use the text/html type. the data for this type should be serialized html source code. for example, it would be suitable to set its data to the value of the innerhtml property of ...
IDBCursor.continuePrimaryKey() - Web APIs
the continueprimarykey() method of the idbcursor interface advances the cursor to the to the item whose key matches the key parameter as well as whose primary key matches the primary key parameter. a typical use case, is to resume the iteration where a previous cursor has been closed, without having to compare the keys one by one. calling this method more than once before new cursor data has been loaded - for example, calling continueprimarykey() twice from the same onsuccess handler - results in an invalidstateerror being thrown on the second call because the cursor’s got value flag has been unset. this method is only valid for cursors coming from an index. using it for cursors coming from an object store will throw an error. note: this feature is available in web workers. syntax curso...
IDBDatabase.createObjectStore() - Web APIs
rison) already exists in the connected database. invalidaccesserror if autoincrement is set to true and keypath is either an empty string or an array containing an empty string. example // let us open our database var request = window.indexeddb.open("todolist", 4); // this handler is called when a new version of the database // is created, either when one has not been created before // or when a new version number is submitted by calling // window.indexeddb.open(). // this handler is only supported in recent browsers. request.onupgradeneeded = function(event) { var db = event.target.result; db.onerror = function(event) { note.innerhtml += "<li>error loading database.</li>"; }; // create an objectstore for this database var objectstore = db.createobjectstore(...
IDBDatabase - Web APIs
li>'; // store the result of opening the database in the db // variable. ...
IDBKeyRange.upperBound() - Web APIs
e. exceptions this method may raise a domexception of the following type: exception description dataerror the value parameter passed was not a valid key. example the following example illustrates how you'd use an upper bound key range. here we declare keyrangevalue = idbkeyrange.upperbound("f"); — a range that includes the value "f" and everything before it. we open a transaction (using idbtransaction) and an 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. note: for a more complete example allowing you to experiment with key range, have a look at ou...
IDBObjectStore.createIndex() - Web APIs
'<li>database initialised.</li>'; // store the result of opening the database in the db variable. // this is used a lot below. db = request.result; // run the displaydata() function to populate the task list with // all the to-do list data already in the idb displaydata(); }; // this handler fires when a new database is created and indicates // either that one has not been created before, or a new version // was submitted with window.indexeddb.open(). (see above.) // it is only implemented in recent browsers. dbopenrequest.onupgradeneeded = function(event) { var db = event.target.result; db.onerror = function(event) { note.innerhtml += '<li>error loading database.</li>'; }; // create an objectstore for this database var objectstore = db.createobjectstore("todolist...
IDBObjectStore.deleteIndex() - Web APIs
i>database initialised.</li>'; // store the result of opening the database in the db variable. ...
IDBObjectStore - Web APIs
// 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 db. ...
IDBOpenDBRequest.onblocked - Web APIs
lised.</li>'; // store the result of opening the database in the db variable. // this is used a lot below db = request.result; // run the displaydata() function to populate the task list with // all the to-do list data already in the idb displaydata(); }; // this event handles the event whereby a new version of the // database needs to be created. ...
IDBOpenDBRequest.onupgradeneeded - Web APIs
ed to update the database structure if a database with a higher version number is loaded. for a full working example, see our to-do notifications app (view example live.) var db; // request version 3 of the database. var request = window.indexeddb.open("library", 3); // this event handles the event whereby a new version of the // database needs to be created. either one has not been created // before, or a new version number has been submitted via the // window.indexeddb.open line above. request.onupgradeneeded = function(event) { db = request.result; db.onerror = function(errorevent) { note.innerhtml += '<li>error loading database.</li>'; }; if (event.oldversion < 1) { // version 1 is the first version of the database. var store = db.createobjectstore("books", {keypath:...
IDBOpenDBRequest - Web APIs
d.</li>'; // store the result of opening the database in the db // variable. ...
IDBVersionChangeRequest.setVersion() - Web APIs
warning: the latest draft of the specification has dropped this method. some not up-to-date browsers still implement this method. ...
IIRFilterNode.getFrequencyResponse() - Web APIs
the getfrequencyresponse() method of the iirfilternode interface takes the current filtering algorithm's settings and calculates the frequency response for frequencies specified in a specified array of frequencies. the two output arrays, magresponseoutput and phaseresponseoutput, must be created before calling this method; they must be the same size as the array of input frequency values (frequencyarray). syntax iirfilternode.getfrequencyresponse(frequencyarray, magresponseoutput, phaseresponseoutput); parameters frequencyarray a float32array containing an array of frequencies, specified in hertz, which you want to filter. magresponseoutput a float32array to receive the computed magnitudes of the freqency response for each frequency value in the frequencyarray. phaseresponseoutput...
IdleDeadline.timeRemaining() - Web APIs
for example, if the callback finishes a task and has another one to begin, it can call timeremaining() to see if there's enough time to complete the next task. if there isn't, the callback can just return immediately, or look for other work to do with the remaining time. ...
IdleDeadline - Web APIs
e timeout specified when the idle callback was installed has expired. methods idledeadline.timeremaining() returns a domhighrestimestamp, which is a floating-point value providing an estimate of the number of milliseconds remaining in the current idle period. if the idle period is over, the value is 0. your callback can call this repeatedly to see if there's enough time left to do more work before returning. example see our complete example in the article cooperative scheduling of background tasks api. specifications specification status comment cooperative scheduling of background tasks proposed recommendation ...
InputEvent() - Web APIs
be an empty string if the change doesn't insert text (such as when deleting characters, for example). datatransfer: (optional) a datatransfer object containing information about richtext or plaintext data being added to or removed from editible content. iscomposing: (optional) a boolean indicating that the event is part of a composition session, meaning it is after a compositionstart event but before a compositionend event. the default is false. ranges: (optional) an array of static ranges that will be affected by a change to the dom if the input event is not canceled. the inputeventinit dictionary also accepts fields from uieventinit and from eventinit dictionaries. ...
InputEvent.isComposing - Web APIs
the inputevent.iscomposing read-only property returns a boolean value indicating if the event is fired after compositionstart and before compositionend. syntax var bool = event.iscomposing; example var inputevent = new inputevent('syntheticinput', false); console.log(inputevent.iscomposing); // return false specifications specification status comment document object model (dom) level 3 events specificationthe definition of 'inputevent.iscomposing' in that specification. obsolete initial definition. ...
InputEvent - Web APIs
ut richtext or plaintext data being added to or removed from editable content. inputevent.inputtyperead only returns the type of change for editable content such as, for example, inserting, deleting, or formatting text. see the property page for a complete list of input types. inputevent.iscomposingread only returns a boolean value indicating if the event is fired after compositionstart and before compositionend. methods this interface inherits methods from its parents, uievent and event. inputevent.gettargetranges() returns an array of static ranges that will be affected by a change to the dom if the input event is not canceled. specifications specification status comment input events level 2the definition of 'inputevent' in that specification. wor...
Timing element visibility with the Intersection Observer API - Web APIs
s = adbox.dataset.totalviewtime / 1000; let sec = math.floor(totalseconds % 60); let min = math.floor(totalseconds / 60); timerbox.innertext = min + ":" + sec.tostring().padstart(2, "0"); } this code finds the ad's timer using its id, "timer", and computes the number of seconds elapsed by dividing the ad's totalviewtime by 1000. then it calculates the number of minutes and seconds elapsed before setting the timer's innertext to a string representing that time in the form m:ss. the string.padstart() method is used to ensure that the number of seconds is padded out to two digits if it's less than 10. building the page contents the buildcontents() function is called by the startup code to select and insert into the document the articles and ads to be presented: let loremipsum = "<p>lorem...
KeyboardEvent.initKeyEvent() - Web APIs
lso be large incompatibilities between implementations and the behavior may change in the future. the keyboardevent.initkeyevent() method is used to initialize the value of an event created using document.createevent("keyboardevent"). events initialized in this way must have been created with the document.createevent("keyboardevent") method. initkeyevent() must be called to set the event before it is dispatched. do not use this method anymore, use the keyboardevent() constructor instead. this method is based on early drafts of document object model (dom) level 2 events specification and is implemented in gecko-based browsers; other browsers implemented keyboardevent.initkeyboardevent based on early drafts of document object model (dom) level 3 events specification. favor the modern...
KeyboardEvent.isComposing - Web APIs
syntax var bool = event.iscomposing; example var kbdevent = new keyboardevent("synthetickey", false); console.log(kbdevent.iscomposing); // return false specifications specification status comment ui eventsthe definition of 'keyboardevent.prototype.iscomposing' in that specification. ...
Key Values - Web APIs
ion). keycode_tv_terrestrial_analog (235) "tvterrestrialdigital" selects digital terrestrial television service (digital cable or antenna receiption). keycode_tv_terrestrial_digital (236) "tvtimer" timer programming button. keycode_tv_timer_programming (258) [1] firefox added proper support for the "tv" key in firefox 37; before that, this key generated the key code "live". [2] these keys were "unidentified" until firefox 37. media controller keys because modern remote controls for media devices often include buttons beyond the basic controls covered elsewhere in this document, key values are defined for a broad array of these additional buttons. the values below are derived in part form a number of consumer electron...
LayoutShiftAttribution - Web APIs
the layoutshiftattribution interface of the layout instability api provides debugging information about elements which have shifted. properties layoutshiftattribution.node returns the element that has shifted (null if it has been removed). layoutshiftattribution.previousrect returns a domrect representing the position of the element before the shift. layoutshiftattribution.currentrect returns a domrect representing the position of the element after the shift. specifications specification status comment layout instability apithe definition of 'layoutshiftattribution' in that specification. editor's draft initial definition. ...
Location: password - Web APIs
Web › API › Location › password
if it is set without first setting the username property, it silently fails. ...
Location: username - Web APIs
Web › API › Location › username
the username property of the location interface is a usvstring containing the username specified before the domain name. syntax string = object.username; object.username = string; examples // let's <a id="myanchor" href="https://anonymous:flabada@developer.mozilla.org/docs/location.username"> be in the document var anchor = document.getelementbyid("myanchor"); var result = anchor.username; // returns:'anonymous' ...
Location - Web APIs
Web › API › Location
id="hash" title="hash">#bang</span></span> css html, body {height:100%;} html {display:table; width:100%;} body {display:table-cell; text-align:center; vertical-align:middle; font-family:georgia; font-size:230%; line-height:1em; white-space:nowrap;} [title] {position:relative; display:inline-block; box-sizing:border-box; /*border-bottom:.5em solid;*/ line-height:2em; cursor:pointer;} [title]:before {content:attr(title); font-family:monospace; position:absolute; top:100%; width:100%; left:50%; margin-left:-50%; font-size:40%; line-height:1.5; background:black;} [title]:hover:before, :target:before {background:black; color:yellow;} [title] [title]:before {margin-top:1.5em;} [title] [title] [title]:before {margin-top:3em;} [title]:hover, :target {position:relative; z-index:1; outline:50em so...
LockManager.request() - Web APIs
ple to only wait for a lock for a short period of time, use the signal option. const controller = new abortcontroller(); // wait at most 200ms. settimeout(() => controller.abort(), 200); try { await navigator.locks.request('my_resource', {signal: controller.signal}, async lock => { // the lock was acquired! }); } catch (ex) { if (ex.name === 'aborterror') { // the request aborted before it could be granted. } } specifications specification status comment web locks apithe definition of 'request()' in that specification. draft initial definition. ...
LockedFile.flush() - Web APIs
Web › API › LockedFile › flush
ompatibilities between implementations and the behavior may change in the future. summary the flush method is used to ensure any change made to a file is properly written on disk. for performance reasons, a lockedfile object buffers all its operation in memory. this allows fast writing and reading operations. periodically, the data are written onto disk. however, if something goes wrong before that, some operations can be lost. to avoid that, it's possible to force a write onto the disk by calling the flush method. syntax var request = instanceoflockedfile.flush(); return a filerequest object to handle the success or failure of the operation. specifications specification status comment filesystem api editor's draft draft proposal ...
MSCandidateWindowShow - 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. mscandidatewindowshow fires immediately after the input method editor (ime) candidate window is set to appear, but before it renders. this proprietary method is specific to internet explorer. general info synchronous no bubbles no cancelable no note windows 8.1 and windows 7 imes for certain languages on internet explorer for the desktop might not support this event. on internet explorer in the new windows ui, this event is supported in windows 8.1 imes of all languages. syntax event property...
MSCandidateWindowUpdate - Web APIs
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. mscandidatewindowupdate fires after the input method editor (ime) candidate window has been identified as needing to change size, but before any visual updates have rendered. this proprietary method is specific to internet explorer. general info synchronous no bubbles no cancelable no note windows 8.1 and windows 7 imes for certain languages on internet explorer for the desktop might not support this event. on internet explorer in the new windows ui, this event is supported in windows 8.1 imes of all languages. syntax ...
MediaDevices.getUserMedia() - Web APIs
d rules, how they are reflected in the context in which your code is running, and about how browsers manage user privacy and security issues, read on. user privacy as an api that may involve significant privacy concerns, getusermedia() is held by the specification to very specific requirements for user notification and permission management. first, getusermedia() must always get user permission before opening any media gathering input such as a webcam or microphone. browsers may offer a once-per-domain permission feature, but they must ask at least the first time, and the user must specifically grant ongoing permission if they choose to do so. of equal importance are the rules around notification. browsers are required to display an indicator that shows that a camera or microphone is in use, ...
MediaElementAudioSourceNode - Web APIs
diosourcenode object instance. properties inherits properties from its parent, audionode. mediaelement read only the htmlmediaelement used when constructing this mediastreamaudiosourcenode. methods inherits methods from its parent, audionode. example this simple example creates a source from an <audio> element using createmediaelementsource(), then passes the audio through a gainnode before feeding it into the audiodestinationnode for playback. when the mouse pointer is moved, the updatepage() function is invoked, which calculates the current gain as a ratio of mouse y position divided by overall window height. you can therefore increase and decrease the volume of the playing music by moving the mouse pointer up and down. note: you can also view this example running live, or view ...
MediaStream Image Capture API - Web APIs
eam. do this by calling mediastream.getvideotracks(). this returns an array of mediastreamtrack objects. the code below assumes that the first item in the mediastreamtrack array is the one to use. you can use the properties of the mediastreamtrack objects to select the one you need. const track = mediastream.getvideotracks()[0]; at this point, you might want to configure the device capabilities before capturing an image. you can do this by calling applyconstraints() on the track object before doing anything else. let zoom = document.queryselector('#zoom'); const capabilities = track.getcapabilities(); // check whether zoom is supported or not. if(!capabilities.zoom) { return; } track.applyconstraints({ advanced : [{ zoom: zoom.value }] }); finally, pass the mediastreamtrack object to the ...
MediaTrackSettings.noiseSuppression - Web APIs
lets you determine what value was selected to comply with your specified constraints for this property's value as described in the mediatrackconstraints.noisesuppression property you provided when calling either getusermedia() or mediastreamtrack.applyconstraints(). noise suppression automatically filters the audio to remove background noise, hum caused by equipment, and the like from the sound before delivering it to your code. this feature is typically used on microphones, although it is technically possible it could be provided by other input sources as well. if needed, you can determine whether or not this constraint is supported by checking the value of mediatracksupportedconstraints.noisesuppression as returned by a call to mediadevices.getsupportedconstraints(). however, typically this...
MediaTrackSupportedConstraints - Web APIs
devices.getsupportedconstraints(). because of the way interface definitions in webidl work, if a constraint is requested but not supported, no error will occur. instead, the specified constraints will be applied, with any unrecognized constraints stripped from the request.that can lead to confusing and hard to debug errors, so be sure to use getsupportedconstraints() to retrieve this information before attempting to establish constraints if you need to know the difference between silently ignoring a constraint and a constraint being accepted. an actual constraint set is described using an object based on the mediatrackconstraints dictionary. to learn more about how constraints work, see capabilities, constraints, and settings. properties some combination—but not necessarily all—of the f...
Using the Media Capabilities API - Web APIs
ability to detect when the device switches gpus, so you can make appropriate adjustments based on the new gpu's capabilities. note: the display capabilities functionality mentioned in the third point above have not yet appeared in any browser. they will be a useful feature of the api once available, but there is a high probability of the display capabilities functionality changing a great deal before browser implementations arrive. the mediacapabilities interface the mediacapabilities is available using the mediacapabilities property which is provided by both the navigator object and the workernavigator object; in other words, the media capabilities api is available both on the main thread and from workers. if the object exists, media capabilities api is available. you can, therefore, tes...
MessagePort: message event - Web APIs
this is only needed when using the addeventlistener() method: if the receiver uses onmessage instead, start() is called implicitly: window.addeventlistener('message', (event) => { const myport = event.ports[0]; myport.onmessage = (event) => { received.textcontent = event.data; }; }); specifications specification stat...
MessagePort: messageerror event - Web APIs
this is only needed when using the addeventlistener() method: if the receiver uses onmessage instead, start() is called implicitly: window.addeventlistener('message', (event) => { const myport = event.ports[0]; myport.onmessage = (event) => { received.textcontent = event.data; }; myport.onmessageerror = (event) => { c...
MouseEvent.initMouseEvent() - Web APIs
once dispatched, it doesn't do anything anymore. do not use this method anymore as it is deprecated. ...
msFirstPaint - Web APIs
me when the document began to be displayed or 0 if the document could not be loaded. the numerical value reported represents the number of milliseconds between the recorded time and midnight january 1, 1970 (utc). this property is supported only for documents displayed in ie9 standards mode. example the following example shows how to calculate the time that is required to request the document before the document begins to display for the user. var otiming = window.performance.timing; var itimems = otiming.msfirstpaint - otiming.navigationstart; ...
msRealTime - Web APIs
property is specific to internet explorer and microsoft edge. syntax ptr = object.msrealtime; value boolean value set to true indicates that low-latency playback will be enabled on the media element. low-latency playback is useful in communication and some gaming scenarios, but is more demanding on power consumption and less reliable for smooth media playback. you must set the msrealtime before setting the src property in code. msrealtime should not be used in non-real-time or non-communication scenarios, such as audio and/or video playback, as this can affects playback startup latency of audio and video playback. ...
MutationObserver.takeRecords() - Web APIs
return value an array mutationrecord objects, each describing one change applied to the observed portion of the document's dom tree. note: the queue of mutations which have occurred, but not been delivered to the observer's callback is left empty after calling takerecords(). example in this example, we demonstrate how to handle any undelivered mutationrecords by calling takerecords() just before disconnecting the observer. const targetnode = document.queryselector("#someelement"); const observeroptions = { childlist: true, attributes: true } const observer = new mutationobserver(callback); observer.observe(targetnode, observeroptions); /* ...later, when it's time to stop observing... */ /* handle any still-pending mutations */ let mutations = observer.takerecords(); observer.di...
MutationRecord - Web APIs
s, or null. mutationrecord.attributename string returns the local name of the changed attribute, or null. mutationrecord.attributenamespace string returns the namespace of the changed attribute, or null. mutationrecord.oldvalue string the return value depends on the mutationrecord.type. for attributes, it is the value of the changed attribute before the change. for characterdata, it is the data of the changed node before the change. for childlist, it is null. note that for this to work as expected, attributeoldvalue or characterdataoldvalue must be set to true in the corresponding mutationobserverinit parameter of the mutationobserver observe method specifications specification status comme...
Navigator.credentials - Web APIs
uch as a successful sign-in or sign-out. this interface can be used for feature detection. syntax var credentialscontainer = navigator.credentials value the credentialscontainer interface. example if ('credentials' in navigator) { navigator.credentials.get({password: true}) .then(function(creds) { //do something with the credentials. }); } else { //handle sign-in the way you did before. }; specifications specification status comment credential management level 1 working draft initial definition. ...
Navigator.mediaSession - Web APIs
back status. this information can include typical metadata such as the title, artist, and album name of the song being played as well as potentially one or more images containing things like album art, artist photos, and so forth. example in this example, metadata is submitted to the mediasession object. note that the code begins by ensuring that the navigator.mediasession property is available before attempting to use it. if ("mediasession" in navigator){ navigator.mediasession.metadata = new mediametadata({ title: "podcast episode title", artist: "podcast host", album: "podcast name", artwork: [{src: "podcast.jpg"}] }); } specifications specification status comment media session standardthe definition of 'navigator.mediasession' in that spe...
Web-based protocol handlers - Web APIs
cript> </head> <body> <h1>web protocol handler sample</h1> <p>this web page will install a web protocol handler for the <code>web+burger:</code> protocol.</p> </body> </html> activating now, anytime the user activates a link that uses the registered protocol, the browser will route the action to the url supplied when the web application registered. firefox will, by default, prompt the user before handing off the action. example <!doctype html public "-//w3c//dtd html 4.01//en"> <html lang="en"> <head> <title>web protocol handler sample - test</title> </head> <body> <p>hey have you seen <a href="web+burger:cheeseburger">this</a> before?</p> </body> </html> handling the next phase is handling the action. the browser extracts the href from the activated link, combines it with the ur...
Online and offline events - Web APIs
o document.body). ...
Node.appendChild() - Web APIs
Web › API › Node › appendChild
the node.appendchild() method adds a node to the end of the list of children of a specified parent node. if the given child is a reference to an existing node in the document, appendchild() moves it from its current position to the new position (there is no requirement to remove the node from its parent node before appending it to some other node). this means that a node can't be in two points of the document simultaneously. so if the node already has a parent, the node is first removed, then appended at the new position. the node.clonenode() method can be used to make a copy of the node before appending it under the new parent. note that the copies made with clonenode will not be automatically kept in sync. if the given child is a documentfragment, the entire contents of the documentfragment...
Node.compareDocumentPosition() - Web APIs
node on which comparedocumentposition() was called, then both the document_position_contains and document_position_preceding bits would be set, producing a value of 10 (0x0a). example const head = document.head; const body = document.body; if (head.comparedocumentposition(body) & node.document_position_following) { console.log('well-formed document'); } else { console.error('<head> is not before <body>'); } note: because the result returned by comparedocumentposition() is a bitmask, the bitwise and operator must be used for meaningful results. specifications specification status comment domthe definition of 'node.comparedocumentposition()' in that specification. living standard document object model (dom) level 3 core specificationthe definit...
Node.nextSibling - Web APIs
Web › API › Node › nextSibling
onsole.groupend(); </script> /************************************************** the console displays the following: siblings of div-1 1. #text 2. div 3. #text 4. script **************************************************/ in the above example, #text nodes are inserted in the dom where whitespace occurs between tags (i.e. after the closing tag of an element and before the opening tag of the next). the possible inclusion of text nodes must be allowed for when traversing the dom using nextsibling. see the resources in the notes section. specifications specification status comment domthe definition of 'node.nextsibling' in that specification. living standard no change document object model (dom) level 2 core specifica...
Node.replaceChild() - Web APIs
Web › API › Node › replaceChild
childnode.replacewith() may be easier to read and use. syntax parentnode.replacechild(newchild, oldchild); parameters newchild the new node to replace oldchild. if it already exists in the dom, it is first removed. oldchild the child to be replaced. return value the returned value is the replaced node. this is the same node as oldchild. ...
NonDocumentTypeChildNode.nextElementSibling - Web APIs
pull request. desktopmobilechromeedgefirefoxinternet exploreroperasafariandroid webviewchrome for androidfirefox for androidopera for androidsafari on iossamsung internetnextelementsiblingchrome full support 4edge full support 12notes full support 12notes notes before edge 79, this property was only implemented for element, not for characterdata.firefox full support 3.5ie partial support 9notes partial support 9notes notes only implemented for element, not for characterdata. see polyfill.opera full support 10safari ...
Notification.permission - Web APIs
r the current origin to display system notifications. default: the user decision is unknown; in this case the application will act as if permission was denied. examples the following snippet could be used if you wanted to first check whether notifications are supported, then check if permission has been granted for the current origin to send notifications, then request permission if required, before then sending a notification. function notifyme() { // let's check if the browser supports notifications if (!("notification" in window)) { console.log("this browser does not support desktop notification"); } // let's check whether notification permissions have alredy been granted else if (notification.permission === "granted") { // if it's okay let's create a notification ...
Notification.requestPermission() - Web APIs
function notifyme() { // let's check if the browser supports notifications if (!("notification" in window)) { alert("this browser does not support desktop notification"); } // let's check whether notification permissions have already been granted else if (notification.permission === "granted") { // if it's okay let's create a notification var n...
Notification - Web APIs
function notifyme() { // let's check if the browser supports notifications if (!("notification" in window)) { alert("this browser does not support desktop notification"); } // let's check whether notification permissions have already been granted else if (notification.permission === "granted") { // if it's okay let's create a notification var n...
OscillatorNode.stop() - Web APIs
the stop method of the oscillatornode interface specifies the time to stop playing the tone. its parameter is optional and defaults to 0. syntax oscillator.stop(when); // stop playing oscillator at when parameters when optional an optional double representing the audio context time when the oscillator should stop. if a value is not included, it defaults to 0. if the time is equal to or before the current audio context time, the oscillator will stop playing immediately. example the following example shows basic usage of an audiocontext to create an oscillator node. for an applied example, check out our violent theremin demo (see app.js for relevant code). // create web audio api context var audioctx = new (window.audiocontext || window.webkitaudiocontext)(); // create oscillator no...
ParentNode - Web APIs
de.lastelementchild read only returns the last node which is both a child of this parentnode and is an element, or null if there is none. methods parentnode.append() inserts a set of node objects or domstring objects after the last child of the parentnode. domstring objects are inserted as equivalent text nodes. parentnode.prepend() inserts a set of node objects or domstring objects before the first child of the parentnode. domstring objects are inserted as equivalent text nodes. parentnode.queryselector() returns the first element with the current element as root that matches the specified group of selectors. parentnode.queryselectorall() returns a nodelist representing a list of elements with the current element as root that matches the specified group of selectors. parentno...
PasswordCredential.additionalData - Web APIs
additionaldata = formdata formdata = passwordcredential.additionaldata passwordcredential.additionaldata = urlsearchparams ulrsearchparams = passwordcredential.additionaldata value one of a formdata instance, a urlsearchparams instance, or null. example the following example creates a formdata object with an appended csrf token. it then stores the form object in the additionaldata parameter, before sending it to server in a call to fetch. //the options object was previously created. navigator.credentials.get(options).then(function(creds) { if (creds.type == 'password') { var form = new formdata(); var csrf_token = document.queryselector('csrf_token').value; form.append('csrf_token', csrf_token); creds.additionaldata = form; fetch('https://www.example.com', { m...
Path2D - Web APIs
Web › API › Path2D
b-path to the (x, y) coordinates. path2d.lineto() connects the last point in the subpath to the (x, y) coordinates with a straight line. path2d.beziercurveto() adds a cubic bézier curve to the path. it requires three points. the first two points are control points and the third one is the end point. the starting point is the last point in the current path, which can be changed using moveto() before creating the bézier curve. path2d.quadraticcurveto() adds a quadratic bézier curve to the current path. path2d.arc() adds an arc to the path which is centered at (x, y) position with radius r starting at startangle and ending at endangle going in the given direction by anticlockwise (defaulting to clockwise). path2d.arcto() adds a circular arc to the path with the given control points and...
PaymentCurrencyAmount.value - Web APIs
one or more decimal digits 0 through 9, optionally with a decimal point (".") with at least one digit following it to represent fractional units. there must not be any leading or trailing whitespace in the string. for uniformity and consistency, the value is always given using the period (".") as the decimal character, regardless of the user's locale. you need to convert the value to this format before submitting the payment. see the example verifying a properly formatted price below for a simple regular expression that can be used to validate the value string prior to submission. examples representing prices this example represents the price of $42.95 in us dollars: let itemprice = { currency: "usd", value: "42.95" }; this example specifies a price of £7.77: let shippingcost = { ...
PaymentDetailsUpdate - Web APIs
the paymentdetailsupdate dictionary is used to provide updated information to the payment user interface after it has been instantiated. this can be done either by calling the paymentrequestupdateevent.updatewith() method or by using the paymentrequest.show() method's detailspromise parameter to provide a promise that returns a paymentdetailsupdate that updates the payment information before the user interface is even enabled for the first time. properties the paymentdetailsupdate dictionary is based on the paymentdetailsbase dictionary, and inherits its properties, which are included in the list below. displayitems optional an array of paymentitem objects, each describing one line item for the payment request. these represent the line items on a receipt or invoice. error opt...
PaymentRequest.canMakePayment() - Web APIs
the paymentrequest method canmakepayment() determines whether or not the request is configured in a way that is compatible with at least one payment method supported by the user agent. you can call this before calling show() to provide a streamlined user experience when the user's browser can't handle any of the payment methods you accept. for instance, you might call canmakepayment() to determine if the browser will let the user pay using payment request api, and if it won't, you could fall back to another payment method, or offer a list of methods that aren't handled by payment request api (or even provide instructions for paying by mail or by phone). syntax paymentrequest.canmakepayment() .then( canpay => { ... }) .catch( error => { ... }) canpay = await paymentrequest.canmakep...
PaymentRequest.onpaymentmethodchange - Web APIs
nt is fired at the paymentrequest, indicating that the user has changed payment methods within the same payment handler. the paymentmethodchange event is triggered by a user-agent controlled interaction (i.e., the end-user switches from a debit to a credit card in the payment ui). to make sure you receive the event, you should add event listeners to paymentrequest object after instantiation, but before you call show(). examples an example payment method change handler is shown below; this example handles changes made to the payment method when using apple pay, specifically: request.onpaymentmethodchange = ev => { const { type: cardtype } = ev.methoddetails; const newstuff = {}; if (ev.methodname === "https://apple.com/apple-pay") { switch (cardtype) { case "store": //...
PaymentRequest.onshippingaddresschange - Web APIs
geevent) { ... }; examples the shippingaddresschange event is triggered by a user-agent controlled interaction. if the address stored by the user agent changes at any time during a payment process, the event is triggered. to make sure an updated address is included when sending payment information to the server, you should add event listeners for a paymentrequest object after instantiation, but before the call to show(). // initialization of paymentrequest arguments are excerpted for clarity. var payment = new paymentrequest(supportedinstruments, details, options); request.addeventlistener('shippingaddresschange', function(evt) { evt.updatewith(new promise(function(resolve) { updatedetails(details, request.shippingaddress, resolve); })); }); payment.show().then(function(paymentrespo...
PaymentRequest.onshippingoptionchange - Web APIs
hangeevent) { ... }; examples the shippingoptionchange event is triggered by a user-agent controlled interaction. if the option stored by the user agent changes at any time during a payment process, the event is triggered. to make sure an updated option is included when sending payment information to the server, you should add event listeners for a paymentrequest object after instantiation, but before the call to show(). // initialization of paymentrequest arguments are excerpted for clarity. var request = new paymentrequest(supportedinstruments, details, options); // when user selects a shipping address request.addeventlistener('shippingaddresschange', e => { e.updatewith(((details, addr) => { var shippingoption = { id: '', label: '', amount: { currency: 'usd', value...
PaymentRequest: paymentmethodchange event - Web APIs
the methoddetails into a function called calculateservicefee(), which we might create to take the information about the transaction, such as the underlying credit card being used to service the apple pay request, and compute and return an paymentdetailsupdate object that specifies changes to be applied to the paymentrequest in order to add any service fees that the payment method might require. before the event handler returns, it calls the event's paymentmethodchangeevent.updatewith.updatewith() method to integrate the changes into the request. related events merchantvalidation, shippingaddresschange, shippingoptionchange, and payerdetailchange specifications specification status comment payment request apithe definition of 'paymentmethodchange' in that specific...
PaymentRequest.show() - Web APIs
ve performance implications you don't want to deal with: function validateresponse(response) { if (checkallvalues(response) { response.complete("success"); } else { response.complete("fail"); } } see the article using promises for more information if you need more information about working with promises. examples in the following example, a paymentrequest object is instantiated before the show() method is called. this method triggers the user agent's built-in process for retrieving payment information from the user. the show() method returns a promise that resolves to a paymentresponse object when the user interaction is complete. the developer then uses the information in the paymentresponse object to format and send payment data to the server. you should send the payment inf...
PaymentRequest - Web APIs
called with the requestshipping flag set to true. paymentrequest.shippingtype read only secure context returns the type of shipping used to fulfill the transaction. this will be one of shipping, delivery, pickup, or null if a value was not provided in the constructor. methods paymentrequest.canmakepayment() secure context indicates whether the paymentrequest object can make a payment before calling show(). paymentrequest.show() secure context causes the user agent to begin the user interaction for the payment request. paymentrequest.abort() secure context causes the user agent to end the payment request and to remove any user interface that might be shown. events merchantvalidation secure context with some payment handlers (e.g., apple pay), this event handler is called...
Payment processing concepts - Web APIs
payee (or merchant) the merchant—either a person or an organization—whose web site or app wishes to receive money through the payment request api. payer the person or organization making a purchase using a web site or app. ...
Payment Request API - Web APIs
entries which have errors. payererrors a dictionary containing strings providing descriptive explanations of any errors in related to paymentresponse's email, phone, and name attributes. paymentdetailsupdate an object describing changes that need to be made to the payment details in the event that the server needs to update information following the instantiation of the payment interface but before the user begins to interact with it. related dictionaries for the basic card specification basiccardchangedetails an object providing redacted address information that is provided as the methoddetails on the paymentmethodchange event sent to the paymentrequest when the user changes payment information. basiccarderrors an object providing any error messages associated with the fields in th...
PerformanceEntry.entryType - Web APIs
created by calling performance.measure(). paint performancepainttiming domstring either 'first-paint' or 'first-contentful-paint'. longtask performancelongtasktiming domstring reports instances of long tasks example the following example shows the use of the entrytype property. ...
PerformanceEntry.startTime - Web APIs
pends on the performance entry's type: "frame" - returns the timestamp when the frame was started. "mark" - returns the timestamp when the mark was created by a call to performance.mark(). "measure" - returns the timestamp when the measure was created by a call to performance.measure(). "navigation" - returns the timestamp with a value of "0". "resource" - returns the timestamp immediately before the browser starts fetching the resource. this property is read only . syntax entry.starttime; return value a domhighrestimestamp representing the first timestamp when the performance entry was created. note: if the performance entry has an entrytype of "resource" (i.e. the entry is a performanceresourcetiming object), this property returns the performanceentry.fetchstart timestamp. examp...
PerformanceNavigation.redirectCount - Web APIs
this interface of this property is deprecated in the navigation timing level 2 specification. please use the performancenavigationtiming interface instead. the legacy performancenavigation.redirectcount read-only property returns an unsigned short representing the number of redirects done before reaching the page. syntax amount = performancenavigation.redirectcount; specifications specification status comment navigation timingthe definition of 'performancenavigation.redirectcount' in that specification. recommendation initial definition. ...
PerformanceNavigation - Web APIs
n, or a script, or by typing the url in the address bar. type_reload (1) the page was accessed by clicking the reload button or via the location.reload() method. type_back_forward (2) the page was accessed by navigating into the history. type_reserved (255) any other way. performancenavigation.redirectcount read only an unsigned short representing the number of redirects done before reaching the page. methods the performance interface doesn't inherit any methods. performancenavigation.tojson() is a jsonizer returning a json object representing the performancenavigation object. specifications specification status comment navigation timingthe definition of 'performancenavigation' in that specification. recommendation initial definition...
PerformanceResourceTiming.encodedBodySize - Web APIs
the encodedbodysize read-only property represents the size (in octets) received from the fetch (http or cache), of the payload body, before removing any applied content-codings. note: this feature is available in web workers. if the resource is retrieved from an application cache or a local resource, it must return the size of the payload body before removing any applied content-codings. syntax resource.encodedbodysize; return value a number representing the size (in octets) received from the fetch (http or cache), of the payload body, before removing any applied content-codings. example the following example, the value of the size properties of all "resource" type events are logged. function log_sizes(perfentry){ // check for support of the performanceentry.*size properties and pri...
PerformanceResourceTiming.requestStart - Web APIs
the requeststart read-only property returns a timestamp of the time immediately before the browser starts requesting the resource from the server, cache, or local resource. if the transport connection fails and the browser retires the request, the value returned will be the start of the retry request. there is no end property for requeststart. note: this feature is available in web workers. syntax resource.requeststart; return value a domhighrestimestamp representing the time immediately before the browser starts requesting the resource from the server example in the following example, the value of the *start and *end properties of all "resource" type events are logged. function print_performanceentries() { // use getentriesbytype() to just get the "resource" events var p = perfor...
PerformanceResourceTiming.workerStart - Web APIs
if the resource is not intercepted by a service worker the property will always return 0. note: this feature is available in web workers. syntax resource.workerstart; value a domhighrestimestamp. example in the following example, the value of the *start and *end properties of all "resource" type events are logged. ...
PerformanceTiming.domContentLoadedEventStart - Web APIs
this interface of this property is deprecated in the navigation timing level 2 specification. please use the performancenavigationtiming interface instead. the legacy performancetiming.domcontentloadedeventstart read-only property returns an unsigned long long representing the moment, in miliseconds since the unix epoch, right before the parser sent the domcontentloaded event, that is right after all the scripts that need to be executed right after parsing has been executed. syntax time = performancetiming.domcontentloadedeventstart; specifications specification status comment navigation timingthe definition of 'performancetiming.domcontentloadedeventstart' in that specification. recommendation initial definition. ...
PerformanceTiming.domInteractive - Web APIs
main document, that is when its document.readystate changes to 'interactive' and the corresponding readystatechange event is thrown. this property can be used to measure the speed of loading web sites that users feels. nevertheless there are a few caveats that happens if scripts are blocking rendering and not loaded asynchronously or with custom web fonts. check if you are in one of these cases before using this property as a proxy for the user experience of a web site's speed of loading. syntax time = performancetiming.dominteractive; specifications specification status comment navigation timingthe definition of 'performancetiming.dominteractive' in that specification. recommendation initial definition. ...
PerformanceTiming.fetchStart - Web APIs
this interface of this property is deprecated in the navigation timing level 2 specification. please use the performancenavigationtiming interface instead. the legacy performancetiming.fetchstart read-only property returns an unsigned long long representing the moment, in miliseconds since the unix epoch, the browser is ready to fetch the document using an http request. this moment is before the check to any application cache. syntax time = performance.timing.fetchstart; specifications specification status comment navigation timingthe definition of 'performancetiming.fetchstart' in that specification. recommendation initial definition. ...
Using the Performance API - Web APIs
accurate to 5 microseconds (because of hardware or software constraints, for example), the browser can represent the value as a time in milliseconds accurate to a millisecond. the following code example shows the use of domhighrestimestamp and the performance.now() method. the now() method returns a timestamp (of type domhighrestimestamp) that is a discrete point in time. by calling this method before and after a task, the time it takes to do the task can be measured. function calculate_time() { var starttime; var endtime; starttime = performance.now(); do_task(); endtime = performance.now(); return (endtime - starttime); } serializing the performance object json serialization of the performance object is done via the tojson() method. in the following example, json serializat...
Pointer Lock API - Web APIs
(from https://w3c.github.io/pointerlock/#extensions-to-the-element-interface) pointerlockelement and exitpointerlock() the pointer lock api also extends the document interface, adding both a new property and a new method. the new property is used for accessing the currently locked element (if any), and is named pointerlockelement and the new method on document ...
Multi-touch interaction - Web APIs
h interaction. // save this event for later processing (this could be part of a // multi-touch interaction) and update the background color push_event(ev); if (logevents) log("pointerdown: name = " + ev.target.id, ev); update_background(ev); } pointer move the pointermove handler is called when the pointer moves. it may be called multiple times (for example, if the user moves the pointer) before a different event type is fired. in this application, a pointer move is represented by the target's border being set to dashed to provide a clear visual indication that the element has received this event. function pointermove_handler(ev) { // note: if the user makes more than one "simultaneous" touch, most browsers // fire at least one pointermove event and some will fire several pointermove...
PublicKeyCredentialCreationOptions.timeout - Web APIs
note: an analogous option exists for the fetching operation (navigators.credentials.get()), see publickeycredentialrequestoptions.timeout. syntax timeout = publickeycredentialcreationoptions.timeout value a numerical hint, expressed in milliseconds, giving the time to wait for the creation operation to complete. examples var publickey = { timeout: 6000, // accepting to wait for a minute before giving up. challenge: new uint8array(26) /* this actually is given from the server */, rp: { name: "example corp", id : "login.example.com" }, user: { id: new uint8array(26), /* to be changed for each user */ name: "jdoe@example.com", displayname: "john doe", }, pubkeycredparams: [ { type: "public-key", alg: -7 } ] }; navigator.credentials.c...
PublicKeyCredentialCreationOptions - Web APIs
recommendation initial defini...
PushEvent.PushEvent() - Web APIs
ed full support 16disabled disabled from version 16: this feature is behind the enable service workers preference. ...
PushEvent.data - Web APIs
Web › API › PushEvent › data
ed full support 16disabled disabled from version 16: this feature is behind the enable service workers preference. ...
PushManager.hasPermission() - Web APIs
ed full support 16disabled disabled from version 16: this feature is behind the enable service workers preference. ...
PushManager.supportedContentEncodings - Web APIs
ed full support 16disabled disabled from version 16: this feature is behind the enable service workers preference. ...
PushMessageData.arrayBuffer() - Web APIs
efox for androidopera for androidsafari on iossamsung internetarraybuffer experimentalchrome full support 50edge full support ≤79firefox full support 44notes full support 44notes notes extended support releases (esr) before firefox 78 esr do not support service workers and the push api.ie no support noopera full support 37safari no support nowebview android no support nochrome android full support ...
PushMessageData.blob() - Web APIs
roidfirefox for androidopera for androidsafari on iossamsung internetblob experimentalchrome full support 50edge full support ≤79firefox full support 44notes full support 44notes notes extended support releases (esr) before firefox 78 esr do not support service workers and the push api.ie no support noopera full support 37safari no support nowebview android no support nochrome android full support ...
PushMessageData.json() - Web APIs
roidfirefox for androidopera for androidsafari on iossamsung internetjson experimentalchrome full support 50edge full support ≤79firefox full support 44notes full support 44notes notes extended support releases (esr) before firefox 78 esr do not support service workers and the push api.ie no support noopera full support 37safari no support nowebview android no support nochrome android full support ...
PushMessageData.text() - Web APIs
roidfirefox for androidopera for androidsafari on iossamsung internettext experimentalchrome full support 50edge full support ≤79firefox full support 44notes full support 44notes notes extended support releases (esr) before firefox 78 esr do not support service workers and the push api.ie no support noopera full support 37safari no support nowebview android no support nochrome android full support ...
PushMessageData - Web APIs
the pushmessagedata interface of the push api provides methods which let you retrieve the push data sent by a server in various formats. unlike the similar methods in the fetch api, which only allow the method to be invoked once, these methods can be called multiple times. messages received through the push api are sent encrypted by push services and then automatically decrypted by browsers before they are made accessible through the methods of the pushmessagedata interface. properties none. methods pushmessagedata.arraybuffer() extracts the data as an arraybuffer object. pushmessagedata.blob() extracts the data as a blob object. pushmessagedata.json() extracts the data as a json object. pushmessagedata.text() extracts the data as a plain text string. examples self.addeventl...
PushSubscription.getKey() - Web APIs
rome for androidfirefox for androidopera for androidsafari on iossamsung internetgetkey()chrome full support 42edge full support 16firefox full support 44notes full support 44notes notes extended support releases (esr) before firefox 78 esr do not support service workers and the push api.ie no support noopera full support 29safari no support nowebview android no support nochrome android full support ...
PushSubscription.options - Web APIs
hrome for androidfirefox for androidopera for androidsafari on iossamsung internetoptionschrome full support 42edge full support 16firefox full support 44notes full support 44notes notes extended support releases (esr) before firefox 78 esr do not support service workers and the push api.ie no support noopera full support 29safari no support nowebview android no support nochrome android full support ...
RTCConfiguration.iceServers - Web APIs
ll limit the connection to local peers. description how the list of servers you provide is used is up to the implementation of the user agent. while it can be useful to provide a second server as a fallback in case the first is offline, listing too many servers can delay the user's connection being established, depending on the network's performance and how many servers get used for negotiation before a connection is established. if the list of servers is changed while a connection is already active by calling the the rtcpeerconnection method setconfiguration(), no immediate effect occurs. however, the new list of servers is used for any future renegotiation, such as while handling an ice restart. examples the configuration below opens a new peer connection, specifying two servers for the i...
RTCConfiguration - Web APIs
ignored in future calls to rtcpeerconnection.setconfiguration(). icecandidatepoolsize optional an unsigned 16-bit integer value which specifies the size of the prefetched ice candidate pool. the default value is 0 (meaning no candidate prefetching will occur). you may find in some cases that connections can be established more quickly by allowing the ice agent to start fetching ice candidates before you start trying to connect, so that they're already available for inspection when rtcpeerconnection.setlocaldescription() is called. changing the size of the ice candidate pool may trigger the beginning of ice gathering. iceservers optional an array of rtciceserver objects, each describing one server which may be used by the ice agent; these are typically stun and/or turn servers. if this i...
RTCDTMFSender.toneBuffer - Web APIs
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 and will cause insertdtmf() to throw an invalidcharactererror exception. using tone buffer strings for example, if you're writing code to control a voicemail system by sending dtmf codes, you might use a string such as "*,1,5555". in this example, we would send "*" to request access to the vm system, then, after...
RTCDTMFToneChangeEvent.RTCDTMFToneChangeEvent() - Web APIs
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 and will cause insertdtmf() to throw an invalidcharactererror exception. specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'rtcdtmftonechangeevent()' in that specification. candidate recommendation initial definition. ...
RTCDataChannel: close event - Web APIs
the close event is sent to the onclose event handler on an rtcdatachannel instance when the data transport being used for the data channel has closed. before any further data can be transferred using rtcdatachannel, a new data channel instance must be created. bubbles no cancelable no interface event event handler property rtcdatachannel.onclose examples this example sets up a handler for the close event for the rtcdatachannel named dc; its responsibility in this example is to update user interface elements to reflect that there is no longer an ongoing call, and to allow a new call to be started. dc.addeventlistener("close", ev => { messageinputbox.disabled = true; sendbutton.disabled = true; connectbutton.disabled = false; disco...
RTCDataChannel.maxPacketLifeTime - Web APIs
the read-only rtcdatachannel property maxpacketlifetime returns the amount of time, in milliseconds, the browser is allowed to take to attempt to transmit a message, as set when the data channel was created, or null. this limits how long the browser can continue to attempt to transmit and retransmit the message before giving up. syntax var lifetime = adatachannel.maxpacketlifetime; value the number of milliseconds over which the browser may continue to attempt to transmit the message until it either succeeds or gives up. if not set when rtcpeerconnection.createdatachannel() was called to create the data channel, this value is null. example // tbd specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition...
RTCDataChannel.readyState - Web APIs
e default state of a new rtcdatachannel created by the webrtc layer when the remote peer created the channel and delivered to the site or app in a datachannel event of type rtcdatachannelevent. "closing" the process of closing the underlying data transport has begun. it is no longer possible to queue new messages to be sent, but previously queued messages may still be send or received before entering the "closed" state. "closed" the underlying data transport has closed, or the attempt to make the connection failed. example var datachannel = peerconnection.createdatachannel("file transfer"); var sendqueue = []; function sendmessage(msg) { switch(datachannel.readystate) { case "connecting": console.log("connection not open; queueing: " + msg); sen...
RTCDataChannel.send() - Web APIs
different browsers have different limitations on the size of the message you can send. ...
RTCDataChannel - Web APIs
lifetime read only the read-only rtcdatachannel property maxpacketlifetime returns the amount of time, in milliseconds, the browser is allowed to take to attempt to transmit a message, as set when the data channel was created, or null.maxretransmits read only the read-only rtcdatachannel property maxretransmits returns the maximum number of times the browser should try to retransmit a message before giving up, as set when the data channel was created, or null, which indicates that there is no maximum.negotiated read only the read-only rtcdatachannel property negotiated indicates whether the rtcdatachannel's connection was negotiated by the web app (true) or by the webrtc layer (false).ordered read only the read-only rtcdatachannel property ordered indicates whether or not the data channel ...
RTCIceCandidate.usernameFragment - Web APIs
. example although the webrtc infrastructure will filter out obsolete candidates for you after an ice restart, you can do it yourself if you're trying to absolutely minimize the number of messages going back and forth. to do so, you can compare the value of usernamefragment to the current usernamefragment being used for the connection after receiving the candidate from the signaling server and before caling addicecandidate() to add it to the set of possible candidates. when the web app receives a message from the signaling server that includes a candidate to 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. ...
RTCIceServer - Web APIs
strings, each specifying a url which can be used to connect to the server. username optional if the rtciceserver is a turn server, then this is the username to use during the authentication process. avoid specifying an unnecessarily large number of urls in the urls property; the startup time for your connection will go up substantially. every server in the list will be contacted and tried out before one is selected to be used for negotiation. older versions of the webrtc specification included an url property instead of urls; this was changed in order to let you specify multiple addresses for each server in the list, as shown in the example below. obsolete properties the following properties have been removed from the specification and should not be used. url this obsolete propert...
RTCInboundRtpStreamStats.averageRtcpInterval - Web APIs
point value indicating the average interval, in seconds, between transmissions of rtcp packets. this interval is computed following the formula outlined in rfc 1889: a.7. because the interval's value is determined in part by the number of active senders, it will be different for each user of a service. since this value is also used to determine the number of seconds after a stream starts to flow before the first rtcp packet should be sent, the result is that if many users try to start using the service at the same time, the server won't be flooded with rtcp packets coming in all at once. the sending endpoint computes this value when sending compound rtcp packets, which must contain at least an rtcp rr or sr packet and an sdes packet with the cname item. specifications specification ...
RTCOutboundRtpStreamStats.averageRtcpInterval - Web APIs
point value indicating the average interval, in seconds, between transmissions of rtcp packets. this interval is computed following the formula outlined in rfc 1889: a.7. because the interval's value is determined in part by the number of active senders, it will be different for each user of a service. since this value is also used to determine the number of seconds after a stream starts to flow before the first rtcp packet should be sent, the result is that if many users try to start using the service at the same time, the server won't be flooded with rtcp packets coming in all at once. the sending endpoint computes this value when sending compound rtcp packets, which must contain at least an rtcp rr or sr packet and an sdes packet with the cname item. specifications specification ...
RTCPeerConnection() - Web APIs
ignored in future calls to rtcpeerconnection.setconfiguration(). icecandidatepoolsize optional an unsigned 16-bit integer value which specifies the size of the prefetched ice candidate pool. the default value is 0 (meaning no candidate prefetching will occur). you may find in some cases that connections can be established more quickly by allowing the ice agent to start fetching ice candidates before you start trying to connect, so that they're already available for inspection when rtcpeerconnection.setlocaldescription() is called. changing the size of the ice candidate pool may trigger the beginning of ice gathering. iceservers optional an array of rtciceserver objects, each describing one server which may be used by the ice agent; these are typically stun and/or turn servers. if this i...
RTCPeerConnection.canTrickleIceCandidates - Web APIs
tcpeerconnection.setremotedescription(). ideally, your signaling protocol provides a way to detect trickling support, so that you don't need to rely on this property. a webrtc browser will always support trickle ice. if trickling isn't supported, or you aren't able to tell, you can check for a falsy value for this property and then wait until the value of icegatheringstate changes to "completed" before creating and sending the initial offer. that way, the offer contains all of the candidates. syntax var cantrickle = rtcpeerconnection.cantrickleicecandidates; value a boolean that is true if the remote peer can accept trickled ice candidates and false if it cannot. if no remote peer has been established, this value is null. note: this property's value is determined once the local peer has ...
RTCPeerConnection.close() - Web APIs
by the ice agent, including turn permissions. all rtcrtpsender objects are considered to be stopped once this returns (they may still be in the process of stopping, but for all intents and purposes, they're stopped). once this method returns, the signaling state as returned by rtcpeerconnection.signalingstate is closed. make sure that you delete all references to the previous rtcpeerconnection before attempting to create a new one that connects to the same remote peer, as not doing so might result in some errors depending on the browser. example var pc = new rtcpeerconnection(); var dc = pc.createdatachannel("my channel"); dc.onmessage = function (event) { console.log("received: " + event.data); pc.close(); // we decided to close after the first received message }; dc.onopen = functio...
RTCPeerConnection.getStreamById() - Web APIs
properties. if you have code that uses stream, you will need to update, since browsers have begun to remove support for stream. syntax var mediastream = pc.getstream(id); parameters id is a domstring corresponding to the stream to return. example var stream = pc.getstreambyid(mytrackid); if (stream) { console.log("found stream: " + stream.id); } polyfill running the following code before any other code will create rtcpeerconnection.prototype.getstreambyid() if it's not natively available. // from: https://bugs.chromium.org/p/chromium/issues/detail?id=698163&desc=5#c10 rtcpeerconnection.prototype.getstreambyid = function(id) { try { var localstreams = this.getlocalstreams(); var remotestreams = this.getremotestreams(); var i; for (i = 0; i < localstreams.length;...
RTCPeerConnection: iceconnectionstatechange event - Web APIs
cally involve the state starting at new, then transitioning through checking, then connected, and finally completed. however, under certain circumstances, the connected state can be skipped, causing a connection to transition directly from the checking state to completed. this can happen when only the last checked candidate is successful, and the gathering and end-of-candidates signals both occur before the successful negotiation is completed. ice connection state during ice restarts when an ice restart is processed, the gathering and connectivity checking process is started over from the beginning, which will cause the iceconnectionstate to transition to connected if the ice restart was triggered while in the completed state. if ice restart is initiated while in the transient disconnected sta...
RTCPeerConnection.ondatachannel - Web APIs
ion which is called when the datachannel event occurs on an rtcpeerconnection. this event, of type rtcdatachannelevent, is sent when an rtcdatachannel is added to the connection by the remote peer calling createdatachannel(). at the time this event is received, the rtcdatachannel it indicates may not yet actually be open. be sure to wait for the "open" event to be fired on the new rtcdatachannel before using it. syntax rtcpeerconnection.ondatachannel = function; value set this property to be a function you provide which receives as input a single parameter: an rtcdatachannelevent which provides in its channel property the rtcdatachannel which has been created. example pc.ondatachannel = function(ev) { console.log('data channel is created!'); ev.channel.onopen = function() { conso...
RTCPeerConnection.peerIdentity - Web APIs
s succeeds or no further attempts to authenticate occur. note: the promise returned by setremotedescription() cannot resolve until any target peer identity that's been set is validated. if the identity hasn't been validated yet, the promise returned by setremotedescription() will be rejected. if there's no target peer identity, setremotedescription() doesn't need to wait for validation to occur before it resolves. example in this example, a function, getidentityassertion(), is created which asynchronously waits for the peer's identity to be verified, then returns the identity to the caller. if an error occurs and the promise is rejected, this logs the error to the console and returns null to the caller. let pc = new rtcpeerconnection(); /* ... */ async function getidentityassertion(pc) {...
RTCPeerConnection.setConfiguration() - Web APIs
for this method (and even then, probably not a very common use case) is to replace the set of ice servers to be used. two potential scenarios in which this might be done: the rtcpeerconnection was instantiated without specifying any ice servers. if, for example, the rtcpeerconnection() constructor was called with no parameters, you would have to then call setconfiguration() to add ice servers before ice negotiation could begin. renegotiation of the connection is needed, and a different set of ice servers needs to be used for some reason. perhaps the user has moved into a new region, so using new regional ice servers is necessary, for example. in this situation, one might call setconfiguration() to switch to new regional ice servers, then initiate an ice restart. you cannot change the ide...
RTCPeerConnection.setRemoteDescription() - Web APIs
he received offer message, msg, directly into setremotedescription() to tell the user agent's webrtc layer what configuration the caller has proposed using. when our promise fulfillment handler is called, indicating that this has been done, we create a stream, add it to the connection, then create an sdp answer and call setlocaldescription() to set that as the configuration at our end of the call before forwarding that answer to the caller. specifications specification status comment webrtc 1.0: real-time communication between browsersthe definition of 'rtcpeerconnection.setremotedescription()' in that specification. candidate recommendation initial specification. ...
RTCPeerConnection.signalingState - Web APIs
bout the signaling process. because the signaling process is a state machine, being able to verify that your code is in the expected state when messages arrive can help avoid unexpected and avoidable failures. for example, if you receive an answer while the signalingstate isn't "have-local-offer", you know that something is wrong, since you should only receive answers after creating an offer but before an answer has been received and passed into rtcpeerconnection.setlocaldescription(). your code will be more reliable if you watch for mismatched states like this and handle them gracefully. this value may also be useful during debugging, for example. in addition, when the value of this property changes, a signalingstatechange event is sent to the rtcpeerconnection instance. syntax var state ...
RTCRtpCodecParameters - Web APIs
the rtcrtpcodecparameters dictionary, part of the webrtc api, is used to describe the configuration parameters for a single media codec. in addition to being the type of the rtcrtpparameters.codecs property, it's used when calling rtcrtptransceiver.setcodecpreferences() to configure a transceiver's codecs before beginning the offer/answer process to establish a webrtc peer connection. most of the fields in this property take values which are defined and maintained by the internet assigned numbers authority (iana). references to relevant iana documents are provided in the see also section at the end of this article. properties payloadtype optional the rtp payload type used to identify this codec. mimetype optional the codec's mime media type and subtype specified as a domstring of the fo...
RTCRtpReceiver.getCapabilities() static function - Web APIs
s("audio"); the returned set of capabilities is the most optimistic possible list. it is entirely possible that certain combinations of options may fail to work when you actually try to use them. calling rtcrtpreceiver.getcapabilities() doesn't prime the browser in any way to handle media. nothing is loaded, fetched, or otherwise prepared. it's simply a means of determining what might be usable before starting to try to access media. because the set of capabilities available tend to be stable for a length of time (people don't install and uninstall codecs and the like very often), the media capabilities can in whole or in part provide a cross-origin method for identifying a user. for that reason, in privacy-sensitive contexts, the browser may choose to obscure the capabilities; this might be ...
RTCRtpSender.getCapabilities() static function - Web APIs
ies("audio"); the returned set of capabilities is the most optimistic possible list. it is entirely possible that certain combinations of options may fail to work when you actually try to use them. calling rtcrtpsender.getcapabilities() doesn't prime the browser in any way to handle media. nothing is loaded, fetched, or otherwise prepared. it's simply a means of determining what might be usable before starting to try to access media. because the set of capabilities available tend to be stable for a length of time (people don't install and uninstall codecs and the like very often), the media capabilities can in whole or in part provide a cross-origin method for identifying a user. for that reason, in privacy-sensitive contexts, the browser may choose to obscure the capabilities; this might be ...
RTCRtpTransceiver.setCodecPreferences() - Web APIs
given a list of rtcrtpcodeccapability objects specifying the new preferences for each codec. the specified set of codecs and configurations will be used for all future connections including this transceiver until this method is called again. when preparing to open an rtcpeerconnection, you can change the codec parameters from the user agent's default configuration by calling setcodecparameters() before calling either rtcpeerconnection.createoffer() or createanswer(). a guide to codecs supported by webrtc—and each codec's positive and negative characteristics—can be found in codecs used by webrtc. syntax rtcrtptransceiver.setcodecpreferences(codecs) parameters codecs an array of rtcrtpcodeccapability objects, in order of preference, each providing the parameters for one of the tran...
Range.compareBoundaryPoints() - Web APIs
the range.compareboundarypoints() method compares the boundary points of the range with those of another range. syntax compare = range.compareboundarypoints(how, sourcerange); return value compare a number, -1, 0, or 1, indicating whether the corresponding boundary-point of the range is respectively before, equal to, or after the corresponding boundary-point of sourcerange. parameters how a constant describing the comparison method: range.end_to_end compares the end boundary-point of sourcerange to the end boundary-point of range. range.end_to_start compares the end boundary-point of sourcerange to the start boundary-point of range. range.start_to_end compares the start boundary-point of sourcerange to the end boundary-point of range. range.start_to_start compares the st...
Range.comparePoint() - Web APIs
if the reference node is a node of type text, comment, or cdatasection, then offset is the number of characters from the start of reference node. for other node types, offset is the number of child nodes between the start of the reference node. syntax returnvalue = range.comparepoint(referencenode, offset) parameters referencenode the node to compare with the range. offset an integer greater than or equal to zero representing the offset inside the referencenode. ...
Range.getBoundingClientRect() - Web APIs
ample positions a "highlight" rectangle behind the contents of a range. the range's content <b>starts here</b> and continues on until it <b>ends here</b>. ...
Range.toString() - Web APIs
Web › API › Range › toString
urning the text of the range. alerting the contents of a range makes an implicit tostring() call, so comparing range and text through an alert dialog is ineffective. syntax text = range.tostring(); example html <p>this example logs <b>everything</b> between the bold <b>words</b>. look at the output below.</p> <p id="log"></p> javascript const range = document.createrange(); range.setstartbefore(document.getelementsbytagname('b').item(0), 0); range.setendafter(document.getelementsbytagname('b').item(1), 0); document.getelementbyid('log').textcontent = range.tostring(); result specifications specification status comment domthe definition of 'range.tostring()' in that specification. living standard no change. document object model (dom) level 2 t...
ReadableStream.ReadableStream() - Web APIs
m implementation will automatically allocate an arraybuffer with a size of the given integer, and the consumer can also use a default reader. queuingstrategy optional an object that optionally defines a queuing strategy for the stream. this takes two parameters: highwatermark a non-negative integer — this defines the total number of chunks that can be contained in the internal queue before backpressure is applied. size(chunk) a method containing a parameter chunk — this indicates 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 ...
ReportingObserver() - Web APIs
ject allowing you to set the options for creating the object. the available options are: types: an array of strings representing the types of report to be collected by this observer. available types include deprecation, intervention, and crash (although this last type usually isn't retrievable via a reportingobserver). buffered: a boolean that defines whether the reports that were generated before the observer was able to be created should be observable (true) or not (false). examples let options = { types: ['deprecation'], buffered: true } let observer = new reportingobserver(function(reports, observer) { reportbtn.onclick = () => displayreports(reports); }, options); specifications specification status comment reporting apithe definition of 'report...
ReportingObserverOptions - Web APIs
the reportingobserveroptions dictionary of the reporting api allows options to be set in the constructor when creating a reportingobserver. properties types an array of strings representing the types of report to be collected by this observer. available types include deprecation, intervention, and crash. buffered a boolean that defines whether the reports that were generated before the observer was able to be created should be observable (true) or not (false). examples let options = { types: ['deprecation'], buffered: true } let observer = new reportingobserver(function(reports, observer) { reportbtn.onclick = () => displayreports(reports); }, options); specifications specification status comment reporting apithe definition of 'reportingobser...
Reporting API - Web APIs
ers: a callback function that has available as parameters the reports available in the observer's report queue, and a copy of the same reportingobserver object, so observation can be controlled directly from inside the callback. the callback runs when observation starts an options dictionary that allows you to specify the type of reports to collect, and whether the reports that were generated before the observer was able to be created should be observable (buffered: true). methods are then available on the observer to start collecting reports (reportingobserver.observe()), retrieve the reports currently in the report queue (reportingobserver.takerecords()), and disconnect the observer so it can no longer collect records (reportingobserver.disconnect()). reporting api interfaces reporti...
ResizeObserver - Web APIs
. the border box encompasses the content, padding, and border. see the box model for further explanation. resizeobserver avoids infinite callback loops and cyclic dependencies that are often created when resizing via a callback function. it does this by only processing elements deeper in the dom in subsequent frames. implementations should, if they follow the specification, invoke resize events before paint and after layout. constructor resizeobserver() creates and returns a new resizeobserver object. properties none. methods resizeobserver.disconnect() unobserves all observed element targets of a particular observer. resizeobserver.observe() initiates the observing of a specified element. resizeobserver.unobserve() ends the observing of a specified element. examples in the...
Using the Resource Timing API - Web APIs
ted resources). the performanceresourcetiming interface has three properties that can be used to obtain size data about a resource. the transfersize property returns the size (in octets) of the fetched resource including the response header fields plus the response payload body. the encodedbodysize property returns the size (in octets) received from the fetch (http or cache), of the payload body, before removing any applied content-codings. decodedbodysize returns the size (in octets) received from the fetch (http or cache) of the message body, after removing any applied content-codings. the following example demonstrates using these three properties. function display_size_data(){ // check for support of the performanceresourcetiming.*size properties and print their values // if supported.
SVGAnimatedAngle - Web APIs
ic type <angle> which can be animated. interface overview also implement none methods none properties readonly svgangle baseval readonly svgangle animval normative document svg 1.1 (2nd edition) properties name type description baseval svgangle the base value of the given attribute before applying any animations. animval svgangle a read only svgangle representing the current animated value of the given attribute. if the given attribute is not currently being animated, then the svgangle will have the same contents as baseval. the object referenced by animval will always be distinct from the one referenced by baseval, even when the attribute is not animated. me...
SVGAnimatedBoolean - Web APIs
es of type boolean which can be animated. interface overview also implement none methods none properties readonly boolean baseval readonly boolean animval normative document svg 1.1 (2nd edition) properties name type description baseval boolean the base value of the given attribute before applying any animations. animval boolean if the given attribute or property is being animated, contains the current animated value of the attribute or property. if the given attribute or property is not currently being animated, contains the same value as baseval. methods the svganimatedboolean interface do not provide any specific methods. browser compatibility the compa...
SVGAnimatedEnumeration - Web APIs
on and which can be animated. interface overview also implement none methods none properties unsigned short baseval readonly unsigned short animval normative document svg 1.1 (2nd edition) properties name type description baseval unsigned short the base value of the given attribute before applying any animations. animval unsigned short if the given attribute or property is being animated, contains the current animated value of the attribute or property. if the given attribute or property is not currently being animated, contains the same value as baseval. methods the svganimatedenumeration interface do not provide any specific methods. browser compatibility...
SVGAnimatedInteger - Web APIs
tes of basic type <integer> which can be animated. interface overview also implement none methods none properties readonly long baseval readonly long animval normative document svg 1.1 (2nd edition) properties name type description baseval long the base value of the given attribute before applying any animations. animval long if the given attribute or property is being animated, contains the current animated value of the attribute or property. if the given attribute or property is not currently being animated, contains the same value as baseval. methods the svganimatedinteger interface do not provide any specific methods. browser compatibility the compati...
SVGAnimatedLength - Web APIs
ype <length> which can be animated. interface overview also implement none methods none properties readonly svglength baseval readonly svglength animval normative document svg 1.1 (2nd edition) properties name type description baseval svglength the base value of the given attribute before applying any animations. animval svglength if the given attribute or property is being animated, contains the current animated value of the attribute or property. if the given attribute or property is not currently being animated, contains the same value as baseval. methods the svganimatedlength interface do not provide any specific methods. browser compatibility the com...
SVGAnimatedLengthList - Web APIs
which can be animated. interface overview also implement none methods none properties readonly svglengthlist baseval readonly svglengthlist animval normative document svg 1.1 (2nd edition) properties name type description baseval svglengthlist the base value of the given attribute before applying any animations. animval svglengthlist a read only svglengthlist representing the current animated value of the given attribute. if the given attribute is not currently being animated, then the svglengthlist will have the same contents as baseval. the object referenced by animval will always be distinct from the one referenced by baseval, even when the attribute is not anim...
SVGAnimatedNumber - Web APIs
attributes of basic type <number> which can be animated. interface overview also implement none methods none properties float baseval readonly float animval normative document svg 1.1 (2nd edition) properties name type description baseval float the base value of the given attribute before applying any animations. animval float if the given attribute or property is being animated, contains the current animated value of the attribute or property. if the given attribute or property is not currently being animated, contains the same value as baseval. methods the svganimatednumber interface do not provide any specific methods. browser compatibility the compatib...
SVGAnimatedNumberList - Web APIs
which can be animated. interface overview also implement none methods none properties readonly svgnumberlist baseval readonly svgnumberlist animval normative document svg 1.1 (2nd edition) properties svganimatednumberlist.baseval read only is a svgnumberlist that represents the base value of the given attribute before applying any animations. svganimatednumberlist.animval read only is a read only svgnumberlist that represents the current animated value of the given attribute. if the given attribute is not currently being animated, then the svgnumberlist will have the same contents as baseval. the object referenced by animval will always be distinct from the one referenced by baseval, even when the attribut...
SVGAnimatedPreserveAspectRatio - Web APIs
hich can be animated. interface overview also implement none methods none properties readonly float baseval readonly float animval normative document svg 1.1 (2nd edition) properties svganimatedpreserveaspectratio.baseval read only is a svgpreserveaspectratio that represents the base value of the given attribute before applying any animations. svganimatedpreserveaspectratio.animval read only is a svgpreserveaspectratio that represents the current animated value of the given attribute. if the given attribute is not currently being animated, then the svgpreserveaspectratio will have the same contents as baseval. the object referenced by animval is always distinct from the one referenced by baseval, even when ...
SVGAnimatedRect - Web APIs
s of basic svgrect which can be animated. interface overview also implement none methods none properties readonly svgrect baseval readonly svgrect animval normative document svg 1.1 (2nd edition) properties name type description baseval svgrect the base value of the given attribute before applying any animations. animval svgrect a read only svgrect representing the current animated value of the given attribute. if the given attribute is not currently being animated, then the svgrect will have the same contents as baseval. the object referenced by animval will always be distinct from the one referenced by baseval, even when the attribute is not animated. metho...
SVGAnimatedString.baseVal - Web APIs
setter throws domexception. specifications specification status comment scalable vector graphics (svg) 1.1 (second edition) recommendation scalable vector graphics (svg) 2 candidate recommendation 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. ...
SVGAnimatedString - Web APIs
the svganimatedstring interface represents string attributes which can be animated from each svg declaration. you need to create svg attribute before doing anything else, everything should be declared inside this. properties svganimatedstring.animval read only this is a domstring representing the animation value. if the given attribute or property is being animated it contains the current animated value of the attribute or property. if the given attribute or property is not currently being animated, it contains the same value as baseval. svganimatedstring.baseval this is a domstring representing the base value. the base value of the given attribute before applying any animations. setter throws domexception. methods the svganimatedstring interface do not provide any specific methods...
SVGAnimatedTransformList - Web APIs
n be animated. interface overview also implement none methods none properties readonly svgtransformlist baseval readonly svgtransformlist animval normative document svg 1.1 (2nd edition) properties name type description baseval svgtransformlist the base value of the given attribute before applying any animations. animval svgtransformlist a read only svgtransformlist representing the current animated value of the given attribute. if the given attribute is not currently being animated, then the svgtransformlist will have the same contents as baseval. the object referenced by animval will always be distinct from the one referenced by baseval, even when the attribute is...
SVGElement: abort event - Web APIs
this basically implements the standard abort dom event. ...
SVGElement - Web APIs
s no methods, but inherits methods from: documentandelementeventhandlers, element, elementcssinlinestyle, globaleventhandlers, htmlorforeignelement, svgelementinstance events listen to these events using addeventlistener() or by assigning an event listener to the equivalent on... handler property defined on globaleventhandlers or windoweventhandlers. abort fired when page loading is stopped before an svg element has been allowed to load completely. also available via the onabort property. error fired when an svg element does not load properly or when an error occurs during script execution. also available via the onerror property. load fires on an svgelement when it is loaded in the browser. also available via the onload property. resize fired when an svg document is being resized...
Screen.mozBrightness - Web APIs
precision float. you can read and write this attribute even when the screen is disabled, but the backlight is off while the screen is disabled. if you write a value of x into this attribute, the attribute may not have the same value x when you later read it. most screens don't support as many different brightness levels as there are doubles between 0 and 1. the value's precision might be reduced before storing it. syntax let screenbrightness = window.screen.mozbrightness; specifications not part of specification. ...
ScriptProcessorNode.bufferSize - Web APIs
iodata(), 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 each channel of the input buffer, and each sample in each channel, and add a small amount of white noise, before setting that result to be the output sample in each case. note: for a full working example, see our script-processor-node github repo (also view the source code.) var myscript = document.queryselector('script'); var mypre = document.queryselector('pre'); var playbutton = document.queryselector('button'); // create audiocontext and buffer source var audioctx = new audiocontext(); source = aud...
ScriptProcessorNode.onaudioprocess - Web APIs
iodata(), 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 each channel of the input buffer, and each sample in each channel, and add a small amount of white noise, before setting that result to be the output sample in each case. note: for a full working example, see our script-processor-node github repo (also view the source code.) var myscript = document.queryselector('script'); var mypre = document.queryselector('pre'); var playbutton = document.queryselector('button'); // create audiocontext and buffer source var audioctx = new audiocontext(); source...
ScriptProcessorNode - Web APIs
iodata(), 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 each channel of the input buffer, and each sample in each channel, and add a small amount of white noise, before setting that result to be the output sample in each case. note: for a full working example, see our script-processor-node github repo (also view the source code.) var myscript = document.queryselector('script'); var mypre = document.queryselector('pre'); var playbutton = document.queryselector('button'); // create audiocontext and buffer source var audioctx = new audiocontext(); source = aud...
Selection.rangeCount - Web APIs
after the user clicks on the page, rangecount is 1, even if no selection is visible. a user can normally only select one range at a time, so the rangecount will usually be 1. scripting can be used to make the selection contain more than one range. gecko browsers allow multiple selections across table cells. firefox allows to select multiple ranges in the document by using ctrl+click (unless the click within an element with display: table-cell). ...
Selection.setBaseAndExtent() - Web APIs
1, the whole node minus the first child node is included. and so on. focusnode the node at the end of the selection. focusoffset the number of child nodes from the start of the focus node that should be included in the selection. so for example, if the value is 0 the whole node is excluded. if the value is 1, the first child node is included. and so on. note: if the focus position appears before the anchor position in the document, the direction of the selection is reversed — the caret is placed at the beginning of the text rather the end, which matters for any keyboard command that might follow. for example, shift + ➡︎ would cause the selection to narrow from the beginning rather than grow at the end. return value void. exceptions if anchoroffset is larger than the number of ...
Sensor APIs - Web APIs
cked by a feature policy.'); } else if (error.name === 'referenceerror') { console.log('sensor is not supported by the user agent.'); } else { throw error; } } permissions and feature policy sensor readings may not be taken unless the user grants permission to a specific sensor type. do this using the permissions api. a brief example, shown below, requests permission before attempting to use the sensor. navigator.permissions.query({ name: 'accelerometer' }) .then(result => { if (result.state === 'denied') { console.log('permission to use accelerometer sensor is denied.'); return; } // use the sensor. }); an alternative approach is to attempt to use the error and listen for the securityerror. const sensor = new absoluteorientationsensor(); sensor.sta...
ServiceWorkerContainer - Web APIs
istration objects associated with a serviceworkercontainer in an array. the method returns a promise that resolves to an array of serviceworkerregistration. serviceworkercontainer.startmessages() explicitly starts the flow of messages being dispatched from a service worker to pages under its control (e.g. sent via client.postmessage()). this can be used to react to sent messages earlier, even before that page's content has finished loading. examples the example below first checks to see if the browser supports service workers. if supported, the code registers the service worker and determines if the page is actively controlled by the service worker. if it isn't, it prompts the user to reload the page so the service worker can take control. the code also reports any registration failures. ...
ServiceWorkerGlobalScope.oninstall - Web APIs
syntax serviceworkerglobalscope.oninstall = function(event) { ... ...
ServiceWorkerRegistration.navigationPreload - Web APIs
17 full support 17 full support 16disabled disabled from version 16: this feature is behind the enable service workers preference.firefox full support 44notes full support 44notes notes extended support releases (esr) before firefox 78 esr do not support service workers and the push api.ie no support noopera full support 46safari full support 11.1webview android full support 59chrome android full support ...
ServiceWorkerRegistration.unregister() - Web APIs
registration interface unregisters the service worker registration and returns a promise. the promise will resolve to false if no registration was found, otherwise it resolves to true irrespective of whether unregistration happened or not (it may not unregister if someone else just called serviceworkercontainer.register() with the same scope.) the service worker will finish any ongoing operations before it is unregistered. note: this feature is available in web workers. syntax serviceworkerregistration.unregister().then(function(boolean) { }); parameters none. return value promise resolves with a boolean indicating whether the service worker has unregistered or not. example the following simple example registers a service worker example, but then immediately unregisters it again: if ...
ServiceWorkerRegistration - Web APIs
on objects. serviceworkerregistration.shownotification() displays the notification with the requested title. serviceworkerregistration.update() checks the server for an updated version of the service worker without consulting caches. serviceworkerregistration.unregister() unregisters the service worker registration and returns a promise. the service worker will finish any ongoing operations before it is unregistered. examples in this example, the code first checks whether the browser supports service workers and if so registers one. next, it adds an updatefound listener in which it uses the service worker registration to listen for further changes to the service worker's state. if the service worker hasn't changed since the last time it was registered, then the updatefound event will no...
SourceBuffer.abort() - Web APIs
rrent implementations can be useful in certain situations, when you want to stop the current append (or whatever) operation occuring on a sourcebuffer, and then immediately start performing operations on it again. for example, consider this code: sourcebuffer.addeventlistener('updateend', function (_) { ... }); sourcebuffer.appendbuffer(buf); let's say that after the call to appendbuffer but before the updateend event fires (i.e. a buffer is being appended but the operation has not yet completed) a user "scrubs" the video seeking to a new point in time. in this case you would want to manually call abort() on the source buffer to stop the decoding of the current buffer, then fetch and append the newly requested segment that relates to the current new position of the video. you can see some...
SourceBuffer - Web APIs
ebuffer.updating changes from true to false. sourcebuffer.onerror fired whenever an error occurs during sourcebuffer.appendbuffer() or sourcebuffer.appendstream(). sourcebuffer.updating changes from true to false. sourcebuffer.onupdate fired whenever sourcebuffer.appendbuffer() method or the sourcebuffer.remove() completes. sourcebuffer.updating changes from true to false. this event is fired before onupdateend. sourcebuffer.onupdateend fired whenever sourcebuffer.appendbuffer() method or the sourcebuffer.remove() has ended. this event is fired after onupdate. sourcebuffer.onupdatestart fired whenever the value of sourcebuffer.updating transitions from false to true. methods inherits methods from its parent interface, eventtarget. sourcebuffer.abort() aborts the current segment an...
SpeechSynthesis.onvoiceschanged - Web APIs
echsynthesisinstance.onvoiceschanged = function() { ... }; examples this could be used to populate a list of voices that the user can choose between when the event fires (see our speak easy synthesis demo.) note that firefox doesn't support it at present, and will just return a list of voices when speechsynthesis.getvoices() is fired. with chrome however, you have to wait for the event to fire before populating the list, hence the bottom if statement seen below. var voices = []; function populatevoicelist() { voices = synth.getvoices(); for(i = 0; i < voices.length ; i++) { var option = document.createelement('option'); option.textcontent = voices[i].name + ' (' + voices[i].lang + ')'; if(voices[i].default) { option.textcontent += ' -- default'; } option.set...
SpeechSynthesis.speak() - Web APIs
syntax speechsynthesisinstance.speak(utterance); returns void. parameters utterance a speechsynthesisutterance object. examples this snippet is excerpted from our speech synthesiser demo. when a form containing the text we want to speak is submitted, we (amongst other things) create a new utterance containing this text, then speak it by passing it into speak() as a parameter. var synth = window.speechsynthesis; ... ...
SpeechSynthesis - Web APIs
thesisvoice objects representing all the available voices on the current device. speechsynthesis.pause() puts the speechsynthesis object into a paused state. speechsynthesis.resume() puts the speechsynthesis object into a non-paused state: resumes it if it was already paused. speechsynthesis.speak() adds an utterance to the utterance queue; it will be spoken when any other utterances queued before it have been spoken. events listen to this event using addeventlistener() or by assigning an event listener to the oneventname property of this interface. voiceschanged fired when the list of speechsynthesisvoice objects that would be returned by the speechsynthesis.getvoices() method has changed. also available via the onvoiceschanged property. examples first, a simple example: let u...
SpeechSynthesisErrorEvent.error - Web APIs
the error property of the speechsynthesiserrorevent interface returns an error code indicating what has gone wrong with a speech synthesis attempt. syntax myerror = event.error; value a domstring containing an error code. possible codes are: canceled a speechsynthesis.cancel method call caused the speechsynthesisutterance to be removed from the queue before it had begun being spoken. interrupted a speechsynthesis.cancel method call caused the speechsynthesisutterance to be interrupted after it had begun being spoken and before it completed. audio-busy the operation couldn't be completed at this time because the user-agent couldn't access the audio output device (for example, the user may need to correct this by closing another application.) audio-hardware the operation ...
Using the Storage Access API - Web APIs
ly look at a common storage access scenario. usage notes the storage access api is designed to allow embedded content to request access to storage that would otherwise be blocked when a user’s browser is set to block all third-party cookies. since embedded content won’t know which storage policy is in use by the user, it’s best to always check whether the embedded frame has storage access before attempting to read or write from storage. this is particularly true for document.cookie access, as browsers will often return an empty cookie jar when third-party cookies are blocked. accessing a user's cookies 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 cooki...
Streams API - Web APIs
sage 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. previously, if we wanted to process a resource of some kind (be it a video, or a text file, etc.), we'd have to download the entire file, wait for it to be deserialized into a suitable format, then process the whole lot after it is fully received. with streams being available to javascript, this all changes — you can now start processing raw data with javascript bit by bit as soon as it is av...
SubtleCrypto.sign() - Web APIs
Web › API › SubtleCrypto › sign
le for signing. supported algorithms the web crypto api provides four algorithms that can be used for signing and signature verification. three of these algorithms — rsassa-pkcs1-v1_5, rsa-pss, and ecdsa — are public-key cryptosystems that use the private key for signing and the public key for verification. these systems all use a digest algorithm to hash the message to a short fixed size before signing. the choice of digest algorithm is passed into the generatekey() or importkey() functions. the fourth algorithm — hmac — uses the same algorithm and key for signing and for verification: this means that the verification key must be kept secret, which in turn means that this algorithm is not suitable for many signature use cases. it can be a good choice however when the signer and ver...
SubtleCrypto.wrapKey() - Web APIs
encrypt it. this is sometimes called the "wrapping key". the inverse of wrapkey() is subtlecrypto.unwrapkey(): while wrapkey is composed of export + encrypt, unwrapkey is composed of import + decrypt. syntax const result = crypto.subtle.wrapkey( format, key, wrappingkey, wrapalgo ); parameters format is a string describing the data format in which the key will be exported before it is encrypted. it can be one of the following: raw: raw format. pkcs8: pkcs #8 format. spki: subjectpublickeyinfo format. jwk: json web key format. key is the cryptokey to wrap. wrappingkey is the cryptokey used to encrypt the exported key. the key must have the wrapkey usage set. wrapalgo is an object specifying the algorithm to be used to encrypt the exported key, and ...
SyncManager.register() - Web APIs
owonbattery: a boolean that determines whether synchronization is allowed when the user agent is on a battery-powered device. the default is true. id: the unique identifier of the specified syncregistration object. idlerequired: a boolean that determines whether synchronization is allowed when the user agent's device is idle. the default is false. maxdelay: the maximum delay in milliseconds before the next sync event (or the first sync event if it is periodic). the default is 0, meaning there is no maximum delay. mindelay: the minimum delay in milliseconds before the next sync event (or the first sync event if it is periodic). the default is 0. minperiod: the minimum time in milliseconds between periodic sync events. the default is 0, meaning events are not periodic. minrequirednetwo...
TimeEvent - Web APIs
Web › API › TimeEvent
vent type, indicates the repeat number for the animation. timeevent.view read only is a windowproxy that identifies the window from which the event was generated. methods inittimeevent(domstring typearg, abstractview viewarg, long detailarg) the inittimeevent method is used to initialize the value of a timeevent created through the documentevent interface. this method may only be called before the timeevent has been dispatched via the dispatchevent method, though it may be called multiple times during that phase if necessary. ...
Supporting both TouchEvent and MouseEvent - Web APIs
ts 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 requirement that may affect an application. if the browser fires both touch and mouse events because of a single user input, the browser must fire a touchstart before any mouse events. consequently, if an application does not want mouse events fired on a specific touch target element, the element's touch event handlers should call preventdefault() and no additional mouse events will be dispatched. here is a code snippet of the touchmove event handler calling preventdefault(). // touchmove handler function process_touchmove(ev) { // call preventdefault() to...
TreeWalker.previousNode() - Web APIs
the treewalker.previousnode() method moves the current node to the previous visible node in the document order, and returns the found node. it also moves the current node to this one. if no such node exists,or if it is before that the root node defined at the object construction, returns null and the current node is not changed. syntax node = treewalker.previousnode(); example var treewalker = document.createtreewalker( document.body, nodefilter.show_element, { acceptnode: function(node) { return nodefilter.filter_accept; } }, false ); var node = treewalker.previousnode(); // returns null as there is no parent specifications specification status comment domthe definition of 'treewalker.previousnode' in that specification. living standard no...
UIEvent.initUIEvent() - Web APIs
once dispatched, it doesn't do anything anymore. do not use this method anymore as it is deprecated. instead use specific event constructors, like uievent(). the page on creating and triggering events gives more information about the way to use these. ...
URL.password - Web APIs
Web › API › URL › password
if it is set without first setting the username property, it silently fails. note: this feature is available in web workers. syntax const passwordstring = url.password url.password = newpassword value a usvstring. ...
URL.username - Web APIs
Web › API › URL › username
note: this feature is available in web workers. syntax const usernamestring = url.username url.username = newusername value a usvstring. ...
URL API - Web APIs
Web › API › URL API
but it's much easier to create a url object to do it for you. the filltablewithparameters() function below takes as input a htmltableelement object representing a <table>. rows are added to the table, one for each key found in the parameters, with the first column containing the key's name, and the second column having the value. note the call to urlsearchparams.sort() to sort the parameter list before generating the table. function filltablewithparameters(tbl) { let url = new url(document.location.href); url.searchparams.sort(); let keys = url.searchparams.keys(); for (let key of keys) { let val = url.searchparams.get(key); let row = document.createelement("tr"); let cell = document.createelement("td"); cell.innertext = key; row.appendchild(cell); cell = docum...
USBDevice.configuration - Web APIs
the configuration read only property of the usbdevice interface returns a usbconfiguration object for the currently selected interface for a paired usb device. syntax var usbconfiguration = usbdevice.configuration value a usbconfiguration object. example the following example uses this property to test for the existence of a usbconfiguration property to select a configuration before claiming an interface. async function connectdevice(usbdevice) { await usbdevice.open(); if (usbdevice.configuration === null) await usbdevice.selectconfiguration(1); await usbdevice.claiminterface(0); } specifications specification status comment webusbthe definition of 'configuration' in that specification. draft initial definition. ...
USBInTransferResult - Web APIs
received from the usb device, if any. usbintransferresult.statusread only returns the status of the transfer request, one of: "ok" - the transfer was successful. "stall" - the device indicated an error by generating a stall condition on the endpoint. a stall on the control endpoint does not need to be cleared. a stall on a bulk or interrupt endpoint must be cleared by calling clearhalt() before transferin() can be called again. "babble" - the device responded with more data than was expected. specifications specification status comment webusbthe definition of 'usbintransferresult' in that specification. draft initial definition. ...
USBOutTransferResult - Web APIs
enread only returns the number of bytes from the transfer request that were sent to the device. usbouttransferresult.statusread only returns the status of the transfer request, one of: "ok" - the transfer was successful. "stall" - the device indicated an error by generating a stall condition on the endpoint. a stall on a bulk or interrupt endpoint must be cleared by calling clearhalt() before transferout() can be called again. specifications specification status comment webusbthe definition of 'usbouttransferresult' in that specification. draft initial definition. ...
Vibration API - Web APIs
es describes alternating periods in which the device is vibrating and not vibrating. each value in the array is converted to an integer, then interpreted alternately as the number of milliseconds the device should vibrate and the number of milliseconds it should not be vibrating. for example: window.navigator.vibrate([200, 100, 200]); this vibrates the device for 200 ms, then pauses for 100 ms before vibrating the device again for another 200 ms. you may specify as many vibration/pause pairs as you like, and you may provide either an even or odd number of entries; it's worth noting that you don't have to provide a pause as your last entry since the vibration automatically stops at the end of each vibration period. canceling existing vibrations calling navigator.vibrate() with a value of 0,...
VideoPlaybackQuality.droppedVideoFrames - Web APIs
into the htmlvideoelement. syntax value = videoplaybackquality.droppedvideoframes; value an unsigned 64-bit value indicating the number of frames that have been dropped since the last time the media in the <video> element was loaded or reloaded. this information can be used to determine whether or not to downgrade the video stream to avoid dropping frames. frames are typically dropped either before or after decoding them, when it's determined that it will not be possible to draw them to the screen at the correct time. example this example calls getvideoplaybackquality() to obtain a videoplaybackquality object, then determines what percentage of frames have been dropped. that value is then presented in an element for the user's reference. var videoelem = document.getelementbyid("my_vid"...
Visual Viewport API - Web APIs
hod. 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 and the call to requestanimationframe(). the pendingupdate flag serves to prevent multiple invocations of the transfrom that can occur when onresize and onscroll fire at the same time. using requestanimationframe() ensures that the transform ocurrs before the next render. let pendingupdate = false; function viewporthandler(event) { if (pendingupdate) return; pendingupdate = true; requestanimationframe(() => { pendingupdate = false; var layoutviewport = document.getelementbyid('layoutviewport'); // since the bar is position: fixed we need to offset it by the // visual viewport's offset from the layout viewport origin. ...
WaveShaperNode.oversample - Web APIs
the 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...
WaveShaperNode - Web APIs
constructor waveshapernode() creates a new instance of an waveshapernode object. properties inherits properties from its parent, audionode. 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. example the following example shows basic usage of an audiocontext to create a wave shaper node. for applied examples/information, check out our voice-change-o-matic demo (see app.js for relevant code). note: sigmoid functions are commonly used for distortion curves ...
WebGL2RenderingContext.clientWaitSync() - Web APIs
ed. must not be larger than gl.max_client_wait_timeout_webgl. return value a glenum indicating the sync object's status. gl.already_signaled: indicates that the sync object was signaled when this method was called. gl.timeout_expired: indicates that the timeout time passed and that the sync object did not become signaled. gl.condition_satisfied: indicates that the sync object was signaled before the timeout expired. gl.wait_failed: indicates that an error occurred during the execution. examples var sync = gl.fencesync(gl.sync_gpu_commands_complete, 0); var status = gl.clientwaitsync(sync, 0, 0); specifications specification status comment webgl 2.0the definition of 'clientwaitsync' in that specification. editor's draft initial definition for webgl. ...
WebGL2RenderingContext.waitSync() - Web APIs
no-op in the absence of the possibility of synchronizing between multiple gl contexts. syntax void gl.waitsync(sync, flags, timeout); parameters sync a webglsync object on which to wait on. flags a glbitfield specifying a bitwise combination of flags controlling the flushing behavior. must be 0 (exists for extensions only). timeout a glint64 specifying a timeout the server should wait before continuing. must be gl.timeout_ignored. return value none. examples var sync = gl.fencesync(gl.sync_gpu_commands_complete, 0); gl.waitsync(sync, 0, gl.timeout_ignored); specifications specification status comment webgl 2.0the definition of 'waitsync' in that specification. editor's draft initial definition for webgl. opengl es 3.0the definition of 'g...
WebGLRenderingContext.isContextLost() - Web APIs
the webglrenderingcontext.iscontextlost() method returns a boolean indicating whether or not the webgl context has been lost and must be re-established before rendering can resume. syntax let islost = gl.iscontextlost(); return value a boolean which is true if the context is lost, or false if not. usage notes there are several reasons why a webgl context may be lost, making it necessary to re-establish the context before resuming rendering. examples include: two or more pages are using the gpu, but together place too high a demand on the gpu, so the browser tells the two contexts that they've lost the connection, then selects one of the two to restore access for. the user's computer has multiple graphics processors (such as a laptop with both mobile and desktop class gpus, the former ...
WebGLRenderingContext.polygonOffset() - Web APIs
syntax void gl.polygonoffset(factor, units); parameters factor a glfloat which sets the scale factor for the variable depth offset for each polygon. the default value is 0. units a glfloat which sets the multiplier by which an implementation-specific value is multiplied with to create a constant depth offset. the default value is 0. return value none. ...
WebGLRenderingContext.vertexAttribPointer() - Web APIs
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 named attribute from the vertex shader to the index you want to use. this must be done before calling gl.linkprogram(). you can then provide this same index to gl.vertexattribpointer(). alternatively, you use the index that is assigned by the graphics card when compiling the vertex shader. depending on the graphics card, the index will vary, so you must call gl.getattriblocation() to find out the index, and then provide this index to gl.vertexattribpointer(). if you are using webgl 2, ...
A basic 2D WebGL animation example - Web APIs
("error linking shader program:"); console.log(gl.getprograminfolog(program)); } return program; } first, gl.createprogram() is called to create a new, empty, glsl program. then, for each shader in the specified list of shaders, we call a compileshader() function to compile it, passing into it the id and type of the shader function to build. each of those objects includes, as mentioned before, the id of the <script> element the shader code is found in and the type of shader it is. the compiled shader is attached to the shader program by passing it into gl.attachshader(). we could go a step farther here, actually, and look at the value of the <script> element's type attribute to determine the shader type. once all of the shaders are compiled, the program is linked using gl.linkprog...
Clearing with colors - Web APIs
isplayed only if canvas is not supported. --> <canvas>your browser does not seem to support html5 canvas.</canvas> body { text-align : center; } canvas { display : block; width : 280px; height : 210px; margin : auto; padding : 0; border : none; background-color : black; } // run everything inside window load event handler, to make sure // dom is fully loaded and styled before trying to manipulate it, // and to not mess up the global scope. we are giving the event // handler a name (setupwebgl) so that we can refer to the // function object within the function itself. window.addeventlistener("load", function setupwebgl (evt) { "use strict" // cleaning after ourselves. the event handler removes // itself, because it only needs to run once. window.removeeventlis...
Detect WebGL - Web APIs
riables you can tweak are different for each api. <p>[ here would go the result of webgl feature detection ]</p> <button>press here to detect webglrenderingcontext</button> body { text-align : center; } button { display : block; font-size : inherit; margin : auto; padding : 0.6em; } // run everything inside window load event handler, to make sure // dom is fully loaded and styled before trying to manipulate it. window.addeventlistener("load", function() { var paragraph = document.queryselector("p"), button = document.queryselector("button"); // adding click event handler to button. button.addeventlistener("click", detectwebglcontext, false); function detectwebglcontext () { // create canvas element. the canvas is not added to the // document itself, so it is ...
Hello GLSL - Web APIs
gl example demonstrates a very basic glsl shader program that draws a solid color square. note: this example will most likely work in all modern desktop browsers. but it may not work in some mobile or older browsers. if the canvas remains blank, you can check the output of the next example, which draws exactly the same thing. but remember to read through the explanations and code on this page, before moving on to the next. hello world program in glsl a very simple first shader program. <p>hello world! hello glsl!</p> <canvas>your browser does not seem to support html5 canvas.</canvas> body { text-align : center; } canvas { width : 280px; height : 210px; margin : auto; padding : 0; border : none; background-color : black; } button { display : block; font-siz...
Hello vertex attributes - Web APIs
xinwebglcoords]), gl.static_draw); gl.drawarrays(gl.points, 0, 1); }, false); } var buffer; function initializeattributes() { gl.enablevertexattribarray(0); buffer = gl.createbuffer(); gl.bindbuffer(gl.array_buffer, buffer); gl.bufferdata(gl.array_buffer, new float32array([0.0]), gl.static_draw); gl.vertexattribpointer(0, 1, gl.float, false, 0, 0); } window.addeventlistener("beforeunload", cleanup, true); function cleanup() { gl.useprogram(null); if (buffer) gl.deletebuffer(buffer); if (program) gl.deleteprogram(program); } function getrenderingcontext() { var canvas = document.queryselector("canvas"); canvas.width = canvas.clientwidth; canvas.height = canvas.clientheight; var gl = canvas.getcontext("webgl") || canvas.getcontext("experimental-we...
Matrix math for the web - Web APIs
tion, not for speed or memory management. these functions create a lot of new arrays, which can be particularly expensive for real-time operations due to garbage collection. in real production code it would be best to use optimized functions. glmatrix is an example of a library that has a focus on speed and performance. the focus in the glmatrix library is to have target arrays that are allocated before the update loop. translation matrix a translation matrix is based upon the identity matrix, and is used in 3d graphics to move a point or object in one or more of the three directions (x, y, and/or z). the easiest way to think of a translation is like picking up a coffee cup. the coffee cup must be kept upright and oriented the same way so that no coffee is spilled. it can move up in the air o...
Lighting in WebGL - Web APIs
the only thing left is to look up the location of the avertexnormal attribute and the unormalmatrix uniform. const programinfo = { program: shaderprogram, attriblocations: { vertexposition: gl.getattriblocation(s...
WebGL tutorial - Web APIs
gpu). webgl elements can be mixed with other html elements and composited with other parts of the page or page background. this tutorial describes how to use the <canvas> element to draw webgl graphics, starting with the basics. the examples provided should give you some clear ideas what you can do with webgl and will provide code snippets that may get you started in building your own content. before you start using the <canvas> element is not very difficult, but you do need a basic understanding of html and javascript. the <canvas> element and webgl are not supported in some older browsers, but are supported in recent versions of all major browsers. in order to draw graphics on the canvas we use a javascript context object, which creates graphics on the fly. in this tutorial getting sta...
Introduction to the Real-time Transport Protocol (RTP) - Web APIs
ata is secure and authenticated as appropriate. keeping latency to a minimum is especially important for webrtc, since face-to-face communication needs to be performed with as little latency as possible. the more time lag there is between one user saying something and another hearing it, the more likely there is to be episodes of cross-talking and other forms of confusion. key features of rtp before examining rtp's use in webrtc contexts, it's useful to have a general idea of what rtp does and does not offer. rtp is a data transport protocol, whose mission is to move data between two endpoints as efficiently as possible under current conditions. those conditions may be affected by everything from the underlying layers of the network stack to the physical network connection, the intervening n...
Taking still photos with WebRTC - Web APIs
nked to the <video> element, we start it playing by calling htmlmediaelement.play(). the error callback is called if opening the stream doesn't work. this will happen for example if there's no compatible camera connected, or the user denied access. listen for the video to start playing after calling htmlmediaelement.play() on the <video>, there's a (hopefully brief) period of time that elapses before the stream of video begins to flow. to avoid blocking until that happens, we add an event listener to video for the canplay event, which is delivered when the video playback actually begins. at that point, all the properties in the video object have been configured based on the stream's format. video.addeventlistener('canplay', function(ev){ if (!streaming) { height = video.vid...
Writing WebSocket client applications - Web APIs
e json.parse() to convert the json object back into the original object, then examine and act upon its contents. text data format text received over a websocket connection is in utf-8 format. closing the connection when you've finished using the websocket connection, call the websocket method close(): examplesocket.close(); it may be helpful to examine the socket's bufferedamount attribute before attempting to close the connection to determine if any data has yet to be 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-ve...
Inputs and input sources - Web APIs
object which we'll use to track information about the avatar and its worldview. we want the player to be able to use the w, a, s, and d keys to move forward, left, backward, and right. because we are managing the avatar's position as defined by the keyboard and mouse in addition to anything the xr hardware might be doing, we need to maintain that information separately and apply it as a transform before rendering the avatar (or the world from the avatar's point of view). to accomplish that, we include in the avatar object a posdelta property, of type dompoint, which includes the offsets to apply to all three axes in order to adjust the avatar's position (the viewer pose's reference space's origin) to include movement and rotation from the keyboard and mouse. the corresponding code for keyboard...
WebXR permissions and security - Web APIs
among other things, you need to confirm access to device features such as the microphone and/or camera, get permission to use immersive vr mode (if applicable), and so forth. the variety of hardware and software involved in xr brings multiple apis and technologies into play. in this guide, we'll cover how to ensure your app has the permissions it needs to provide a secure and private xr experience. ...
Basic concepts behind Web Audio API - Web APIs
presented as 44.1 khz) is a common sampling frequency. why 44.1khz? firstly, because the hearing range of human ears is roughly 20 hz to 20,000 hz. via the nyquist–shannon sampling theorem, the sampling frequency must be greater than twice the maximum frequency one wishes to reproduce. therefore, the sampling rate has to be greater than 40 khz. secondly, signals must be low-pass filtered before sampling, otherwise aliasing occurs. while an ideal low-pass filter would perfectly pass frequencies below 20 khz (without attenuating them) and perfectly cut off frequencies above 20 khz, in practice a transition band is necessary, where frequencies are partly attenuated. the wider this transition band is, the easier and more economical it is to make an anti-aliasing filter. the 44.1 khz samplin...
Web Audio API best practices - Web APIs
ou're looking to fetch the file and decode it into a buffer. both are legitimate ways of working, however, it's more common to use the former when you are working with full-length tracks, and the latter when working with shorter, more sample-like tracks. media elements have streaming support out of the box. the audio will start playing when the browser determines it can load the rest of the file before playing finishes. you can see an example of how to use this with the web audio api in the using the web audio api tutorial. you will, however, have more control if you use a buffer node. you have to request the file and wait for it to load (this section of our advanced article shows a good way to do it), but then you have access to the data directly, which means more precision, and more precise ...
Migrating from webkitAudioContext - Web APIs
it was first implemented in webkit, and some of its older parts were not immediately removed as they were replaced in the specification, leading to many sites using non-compatible code. in this article, we cover the differences in web audio api since it was first implemented in webkit and how to update your code to use the modern web audio api. the web audio standard was first implemented in webkit, and the implementation was built in parallel with the work on the specification of the api. ...
Web audio spatialization basics - Web APIs
...
Web Authentication API - Web APIs
ified 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 consenting to the registration. after the user verification, the authenticator will create a new asymmetric key pair and safely store the private key for future reference. the public key will beco...
Using the Web Storage API - Web APIs
; document.queryselector('.my-storage').textcontent = json.stringify(e.storagearea); }); here we add an event listener to the window object that fires when the storage object associated with the current origin is changed. as you can see above, the event object associated with this event has a number of properties containing useful information — the key of the data that changed, the old value before the change, the new value after that change, the url of the document that changed the storage, and the storage object itself (which we've stringified so you can see its content). deleting data records web storage also provides a couple of simple methods to remove data. we don't use these in our demo, but they are very simple to add to your project: storage.removeitem() takes a single argumen...
Window: animationend event - Web APIs
bubbles yes cancelable no interface animationevent event handler property onanimationend the original target for this event is the element that had the animation applied. you can listen for this event on the window interface to handle it in the capture or bubbling phases. for full details on this event please see the page on htmlelement: animationend. ...
Window.captureEvents() - Web APIs
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...
Window.closed - Web APIs
Web › API › Window › closed
the window.closed read-only property indicates whether the referenced window is closed or not. syntax const isclosed = windowref.closed; value a boolean. possible values: true: the window has been closed. false: the window is open. examples change the url of a window from a popup the following example demonstrates how a popup window can change the url of the window that opened it. before attempting to change the url, it checks that the current window has an opener using the window.opener property and that the opener isn't closed: // check that an opener exists and is not closed if (window.opener && !window.opener.closed) { window.opener.location.href = 'http://www.mozilla.org'; } note that popups can only access the window that opened them. refreshing a previously opened popup...
Window.convertPointFromNodeToPage() - Web APIs
given a point specified in a particular dom node's coordinate system, the window method convertpointfromnodetopage() returns a point which specifies the same position in the page's coordinate system. this method is non-standard and should not be used. please review the browser compatibility section before using this method, as it's not widely supported (nor is the point object it uses). syntax point = window.convertpointfromnodetopage(node, nodepoint); parameters node the node in whose coordinate system the point specified by nodepoint is described. nodepoint a point object describing a point in node's coordinate system; this point will be converted to the page's coordinate system. return value a point object specifying a point in the page's coordinate system. specifications ...
Window.convertPointFromPageToNode - Web APIs
syntax point = window.convertpointfrompagetonode(node, pagepoint); parameters node the node into whose coordinate system the point is to be converted. ...
Window.focus() - Web APIs
Web › API › Window › focus
makes a request to bring the window to the front. it may fail due to user settings and the window isn't guaranteed to be frontmost before this method returns. syntax window.focus() example if (clicked) { window.focus(); } specification specification status comment html living standardthe definition of 'window.focus()' in that specification. living standard ...
Window.getComputedStyle() - Web APIs
ed from the document.defaultview object. in nearly all cases, this is needless, as getcomputedstyle exists on the window object as well. it's likely the defaultview pattern was a combination of folks not wanting to write a testing spec for window and making an api that was also usable in java. use with pseudo-elements getcomputedstyle can pull style info from pseudo-elements (such as ::after, ::before, ::marker, ::line-marker — see the pseudo-element spec). <style> h3::after { content: ' rocks!'; } </style> <h3>generated content</h3> <script> var h3 = document.queryselector('h3'); var result = getcomputedstyle(h3, ':after').content; console.log('the generated content is: ', result); // returns ' rocks!' </script> notes the returned cssstyledeclaration object contains a...
Window.getDefaultComputedStyle() - Web APIs
<style> h3:after { content: ' rocks!'; } </style> <h3>generated content</h3> <script> var h3 = document.queryselector('h3'), result = getdefaultcomputedstyle(h3, ':after').content; console.log('the generated content is: ', result); // returns 'none' </script> notes the returned value is, in certain known cases, expressly incorrect by deliberate intent. i...
Window.history - Web APIs
Web › API › Window › history
read-only property returns a reference to the history object, which provides an interface for manipulating the browser session history (pages visited in the tab or frame that the current page is loaded in). see manipulating the browser history for examples and details. in particular, that article explains security features of the pushstate() and replacestate() methods that you should be aware of before using them. example history.back(); // equivalent to clicking back button history.go(-1); // equivalent to history.back(); notes for top-level pages you can see the list of pages in the session history, accessible via the history object, in the browser's dropdowns next to the back and forward buttons. for security reasons the history object doesn't allow the non-privileged code to a...
Window: pagehide event - Web APIs
the pagehide event is sent to a window when the browser hides the current page in the process of presenting a different page from the session's history. for example, when the user clicks the browser's back button, the current page receives a pagehide event before the previous page is shown. bubbles no cancelable no interface pagetransitionevent event handler property onpagehide examples in this example, an event handler is established to watch for pagehide events and to perform special handling if the page is being persisted for possible reuse. window.addeventlistener("pagehide", event => { if (event.persisted) { /* the page isn't being discarded, so it can be reused later */ } }, false); this can also be written using the onpa...
window.postMessage() - Web APIs
le for the caller of postmessage to detect when an event handler listening for events sent by postmessage throws an exception. postmessage() schedules the messageevent to be dispatched only after all pending execution contexts have finished. for example, if postmessage() is invoked in an event handler, that event handler will run to completion, as will any remaining handlers for that same event, before the messageevent is dispatched. the value of the origin property of the dispatched event is not affected by the current value of document.domain in the calling window. for idn host names only, the value of the origin property is not consistently unicode or punycode; for greatest compatibility check for both the idn and punycode values when using this property if you expect messages from idn sit...
window.requestIdleCallback() - Web APIs
a function to be called during a browser's idle periods. this enables developers to perform background and low priority work on the main event loop, without impacting latency-critical events such as animation and input response. functions are generally called in first-in-first-out order; however, callbacks which have a timeout specified may be called out-of-order if necessary in order to run them before the timeout elapses. you can call requestidlecallback() within an idle callback function to schedule another callback to take place no sooner than the next pass through the event loop. a timeout option is strongly recommended for required work, as otherwise it's possible multiple seconds will elapse before the callback is fired. syntax var handle = window.requestidlecallback(callback[, option...
Window: resize event - Web APIs
vents. there is a proposal to allow all elements to be notified of resize changes. see resize observer to read the draft document, and github issues to read the on-going discussions. examples window size logger the following example reports the window size each time it is resized. bear in mind that since the example is running in an <iframe>, you'll need to actually get the <iframe> to resize before you see an effect. <p>resize the browser window to fire the <code>resize</code> event.</p> <p>window height: <span id="height"></span></p> <p>window width: <span id="width"></span></p> const heightoutput = document.queryselector('#height'); const widthoutput = document.queryselector('#width'); function reportwindowsize() { heightoutput.textcontent = window.innerheight; widthoutput.textcont...
Window: transitionend event - Web APIs
bubbles yes cancelable yes interface transitionevent event handler property ontransitionend the transitionend event is fired in both directions - as it finishes transitioning to the transitioned state, and when it fully reverts to the default or non-transitioned state. ...
Window: transitionrun event - Web APIs
bubbles yes cancelable no interface transitionevent event handler property ontransitionrun the original target for this event is the element that had the transition applied. you can listen for this event on the window interface to handle it in the capture or bubbling phases. for full details on this event please see the page on htmlelement: transitionrun. ...
WindowEventHandlers.onhashchange - Web APIs
.5) ? 'location1' : 'location2'; } the hashchange event the dispatched hashchange event has the following properties: field type description newurl domstring the new url to which the window is navigating. oldurl domstring the previous url from which the window was navigated. ...
WindowOrWorkerGlobalScope.atob() - Web APIs
...
WindowOrWorkerGlobalScope.btoa() - Web APIs
...
WindowOrWorkerGlobalScope.fetch() - Web APIs
option must be provided. starting with chrome 50, this property also takes a federatedcredential instance or a passwordcredential instance. cache the cache mode you want to use for the request. redirect the redirect mode to use: follow (automatically follow redirects), error (abort with an error if a redirect occurs), or manual (handle redirects manually). in chrome the default is follow (before chrome 47 it defaulted to manual). referrer a usvstring specifying the referrer of the request. this can be a same-origin url, about:client, or an empty string. referrerpolicy specifies the referrer policy to use for the request. 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-u...
WindowOrWorkerGlobalScope.setInterval() - Web APIs
oop(){ settimeout(function() { // your logic here loop(); }, delay); })(); in the above snippet, a named function loop() is declared and is immediately executed. loop() is recursively called inside settimeout() after the logic has completed executing. while this pattern does not guarantee execution on a fixed interval, it does guarantee that the previous interval has completed before recursing. specifications specification status comment html living standardthe definition of 'windoworworkerglobalscope.setinterval()' in that specification. living standard method moved to the windoworworkerglobalscope mixin in the latest spec. html living standardthe definition of 'windowtimers.setinterval()' in that specification. living standard ...
WindowOrWorkerGlobalScope - Web APIs
e is cropped to the rectangle of pixels originating at (sx, sy) with width sw, and height sh. windoworworkerglobalscope.fetch() starts the process of fetching a resource from the network. windoworworkerglobalscope.queuemicrotask() enqueues a microtask—a short function to be executed after execution of the javascript code completes and control isn't being returned to a javascript caller, but before handling callbacks and other tasks. this lets your code run without interfering with other, possibly higher priority, code, but before the browser runtime regains control, potentially depending upon the work you need to complete. windoworworkerglobalscope.setinterval() schedules a function to execute every time a given number of milliseconds elapses. windoworworkerglobalscope.settimeout() sch...
WritableStream.getWriter() - Web APIs
defaultwriter.ready .then(() => { defaultwriter.close(); }) .then(() => { console.log("all chunks written"); }) .catch((err) => { console.log("stream error:", err); }); } const decoder = new textdecoder("utf-8"); const queuingstrategy = new countqueuingstrategy({ highwatermark: 1 }); let result = ""; const writablestream = new writa...
WritableStream - Web APIs
defaultwriter.ready .then(() => { defaultwriter.close(); }) .then(() => { console.log("all chunks written"); }) .catch((err) => { console.log("stream error:", err); }); } const decoder = new textdecoder("utf-8"); const queuingstrategy = new countqueuingstrategy({ highwatermark: 1 }); let result = ""; const writablestream = new writa...
WritableStreamDefaultWriter.WritableStreamDefaultWriter() - Web APIs
defaultwriter.ready .then(() => { defaultwriter.close(); }) .then(() => { console.log("all chunks written"); }) .catch((err) => { console.log("stream error:", err); }); } const decoder = new textdecoder("utf-8"); const queuingstrategy = new countqueuingstrategy({ highwatermark: 1 }); let result = ""; const writablestream = new writa...
WritableStreamDefaultWriter - Web APIs
defaultwriter.ready .then(() => { defaultwriter.close(); }) .then(() => { console.log("all chunks written"); }) .catch((err) => { console.log("stream error:", err); }); } const decoder = new textdecoder("utf-8"); const queuingstrategy = new countqueuingstrategy({ highwatermark: 1 }); let result = ""; const writablestr...
HTML in XMLHttpRequest - Web APIs
r pages (which often have a text/html response body). usage retrieving an html resource as a dom using xmlhttprequest works just like retrieving an xml resource as a dom using xmlhttprequest, except you can't use the synchronous mode and you have to explicitly request a document by assigning the string "document" to the responsetype property of the xmlhttprequest object after calling open() but before calling send(). var xhr = new xmlhttprequest(); xhr.onload = function() { console.log(this.responsexml.title); } xhr.open("get", "file.html"); xhr.responsetype = "document"; xhr.send(); feature detection method 1 this method relies on the "force async" nature of the feature. when you try to set responsetype of an xmlhttprequest object after it is opened as "sync". this throws an error in t...
How to check the security state of an XMLHTTPRequest over SSL - Web APIs
servercert; dump("\tcommon name (cn) = " + cert.commonname + "\n"); dump("\tissuer = " + cert.issuerorganization + "\n"); dump("\torganisation = " + cert.organization + "\n"); dump("\tsha1 fingerprint = " + cert.sha1fingerprint + "\n"); var validity = cert.validity.queryinterface(ci.nsix509certvalidity); dump("\tvalid from " + validity.notbeforegmt + "\n"); dump("\tvalid until " + validity.notaftergmt + "\n"); } } catch(err) { alert(err); } } function test(url) { var req = cc["@mozilla.org/xmlextras/xmlhttprequest;1"].createinstance(); req.open('get', url, true); req.addeventlistener("error", function(e) { var error = createtcperrorfromfailedxhr(req); dumpsecurityinfo(req, error); }, false...
Synchronous and asynchronous requests - Web APIs
note: the effect is asynchronous, because of the use of the worker. this pattern can be useful, for example in order to interact with the server in the background, or to preload content. see using web workers for examples and details. adapting sync xhr use cases to the beacon api there are some cases in which the synchronous usage of xmlhttprequest is not replaceable, like during the unload, beforeunload, and pagehide events. you should consider using the fetch() api with the keepalive flag. when fetch with keepalive isn't available, you can consider using the navigator.sendbeacon() api, which can support these use cases while typically delivering a good ux. the following example shows theoretical analytics code that attempts to submit data to a server by using a synchronous xmlhttprequest...
XMLHttpRequest() - Web APIs
the xmlhttprequest() constructor creates a new xmlhttprequest. for details about how to use xmlhttprequest, see using xmlhttprequest. syntax const request = new xmlhttprequest(); parameters none. return value a new xmlhttprequest object. the object must be prepared by at least calling open() to initialize it before calling send() to send the request to the server. non-standard firefox syntax firefox 16 added a non-standard parameter to the constructor that can enable anonymous mode (see bug 692677). setting the mozanon flag to true effectively resembles the anonxmlhttprequest() constructor described in older versions of the xmlhttprequest specification. const request = new xmlhttprequest(paramsdictionary); parameters (non-standard) objparameters there are two flags yo...
XMLHttpRequest.mozBackgroundRequest - Web APIs
...
XMLHttpRequest.overrideMimeType() - Web APIs
the xmlhttprequest method overridemimetype() specifies a mime type other than the one provided by the server to be used instead when interpreting the data being transferred in a request. this may be used, for example, to force a stream to be treated and parsed as "text/xml", even if the server does not report it as such. this method must be called before calling send(). syntax xmlhttprequest.overridemimetype(mimetype) parameters mimetype a domstring specifying the mime type to use instead of the one specified by the server. if the server doesn't specify a type, xmlhttprequest assumes "text/xml". return value undefined. example this example specifies a mime type of "text/plain", overriding the server's stated type for the data being received. note: if the server doesn't p...
XMLHttpRequest.response - Web APIs
as an arraybuffer, blob, document, javascript object, or domstring, depending on the value of the request's responsetype property. syntax var body = xmlhttprequest.response; value an appropriate object based on the value of responsetype. you may attempt to request the data be provided in a specific format by setting the value of responsetype after calling open() to initialize the request but before calling send() to send the request to the server. the value is null if the request is not yet complete or was unsuccessful, with the exception that when reading text data using a responsetype of "text" or the empty string (""), the response can contain the response so far while the request is still in the loading readystate (3). the response types are described below. "" an empty responsety...
XMLHttpRequest.send() - Web APIs
. if the request method is get or head, the body parameter is ignored and the request body is set to null. if no accept header has been set using the setrequestheader(), an accept header with the type "*/*" (any type) is sent. syntax xmlhttprequest.send(body) parameters body optional a body of data to be sent in the xhr request. this can be: a document, in which case it is serialized before being sent. an xmlhttprequestbodyinit, which per the fetch spec can be a blob, buffersource, formdata, urlsearchparams, or usvstring object. null if no value is specified for the body, a default value of null is used. the best way to send binary content (e.g. in file uploads) is by using an arraybufferview or blob in conjunction with the send() method. return value undefined. exceptio...
XMLHttpRequest.setRequestHeader() - Web APIs
if this method is called several times with the same header, the values are merged into one single request header. each time you call setrequestheader() after the first time you call it, the specified text is appended to the end of the existing header's content. if no accept header has been set using this, an accept header with the type "*/*" is sent with the request when send() is called. ...
XMLHttpRequest.status - Web APIs
browsers also report a status of 0 in case of xmlhttprequest errors. ...
XMLHttpRequest.timeout - Web APIs
the xmlhttprequest.timeout property is an unsigned long representing the number of milliseconds a request can take before automatically being terminated. the default value is 0, which means there is no timeout. timeout shouldn't be used for synchronous xmlhttprequests requests used in a document environment or it will throw an invalidaccesserror exception. when a timeout happens, a timeout event is fired. note: you may not use a timeout for synchronous requests with an owning window. using a timeout with an asynchronous request in internet explorer, the timeout property may be set only after calling the open() method and before calling the send() method. example var xhr = new xmlhttprequest(); xhr.open('get', '/server', true); xhr.timeout = 2000; // time in milliseconds xhr.onlo...
XRInputSource - Web APIs
a primary action begins, a selectstart event is sent to the xrsession. when the action has completed (such as when the user releases the button), a select event is sent. finally, once that is done—or if the user aborts the action—a selectend event is sent to the session object. an action may be aborted either by the user in some device-specific fashion or if the input device is disconnected before the action is completed. local coordinate system each input source has its own local coordinate system, which is described by the gripspace property, which is an xrspace used to map the input's coordinate system into the world coordinate system. the grip space's coordinate system can then be used to render objects so they appear to be held in the user's hand. for more details on the input so...
XRInputSourceArray.length - Web APIs
alue indicating the number of items in the input source list represented by the xrinputsourcearray object. syntax let inputsourcecount = xrinputsourcearray.length; value an integer value indicating the number of xrinputsource objects representing webxr input sources are includled in the array. examples in this example, a game that requires at least one input source uses length to check this before proceeding to allow the user to play the game. let sources = xrsession.inputsources; if (sources.length === 0) { showalertdialog("you need to have at least one controller to play super duper shark jump fest 9000.", [ { label: "shop now", url: "https://www.amazon.com/s?k=vr+controllers" }, { label: "quit" handler: quitgame } ...
XRPermissionDescriptor - Web APIs
ethod is called, specifying the permission descriptor we've established, xrpermissiondesc. when the returned promise resolves, we check the returned status. if permission has been granted, we call a function setupxr() that handles preparing the webxr environment for use. if permission is conditional based on prompting, we call a function promptandsetupxr() that would handle asking for permission before enabling and starting up the environment. and for any other returned state—which is almost certainly denied, which is the only other option as of this article's writing—we do nothing, since we can't use webxr. if the permission request promise is rejected, the error is handled (currently by just dumping it to the console using domxref("console.log()")}}). if the permissions api isn't availa...
XRReferenceSpace.getOffsetReferenceSpace() - Web APIs
ntation when calling new xrrigidtransform(). the new xrrigidtransform's reference space is then fetched and returned to the caller. this new reference space is one in which the viewer's position is unchanged, but their orientation has been altered based on the pitch and yaw values generated from the accumulated mouse inputs. applymousemovement() should be called when drawing a frame, immediately before fetching the viewer's pose using getviewerpose(), and the rendering should be performed in this reference space. you can see code similar to this in use in our broader webxr tutorial article called movement, orientation, and motion. in particular, check out the section called starting the webxr session. specifications specification status comment webxr device apithe def...
XRReferenceSpaceEvent() - Web APIs
indicating the event type which has occurred. currently, this is always reset. eventinitdict an object based on the xrreferencespaceeventinit dictionary, containing data used to initialize the new event object. the properties of this object are: referencespace the xrreferencespace from which the event originated. transform an xrrigidtransform which maps the old coordinate system (from before the changes indicated by this event) to the new coordiante system. return value a new xrreferencespaceevent object, initialized as defined by the input parameters. specifications specification status comment webxr device apithe definition of 'xrreferencespaceevent()' in that specification. working draft initial definition. ...
XRReferenceSpaceEvent - Web APIs
on the parent interface, event, xrreferencespaceevent objects include the following properties: referencespace read only an xrreferencespace indicating the reference space that generated the event. transform read only an xrrigidtransform object indicating the position and orientation of the specified referencespace's native origin after the event, defined relative to the coordinate system before the event. methods while xrreferencespaceevent does not define any methods, it inherits the methods of its parent interface, event. event types reset the reset event is sent to a reference space when its native origin is changed due to a discontinuity, recalibration, or device reset. this is an opportunity for your app to update any stored transforms, position/orientation information, or ...
XRReferenceSpaceEventInit - Web APIs
to provide the values for its properties. since the properties are read-only, this is the only opportunity available to set their values. you will not usually need to use this, since these events are created by the webxr infrastructure. properties referencespace the xrreferencespace from which the event originated. transform an xrrigidtransform which maps the old coordinate system (from before the changes indicated by this event) to the new coordiante system. usage notes all of this dictionary's properties must have valid values set on them before calling the xrreferencespaceevent() constructor. examples this simple snippet calls the constructor to create a new reference space event of type reset. let refspaceevent = new xrreferencespaceevent("reset", { referencespace: myre...
XRRenderState - Web APIs
hich content should be rendered, the vertical field of view (for inline presentations), and a reference to the xrwebgllayer being used as the target for rendering the scene prior to it being presented on the xr device's display or displays. when you apply changes using the xrsession method updaterenderstate(), the specified changes take effect after the current animation frame has completed, but before the next one begins. properties the followiing properties are available on xrrenderstate objects. baselayer read only the xrwebgllayer from which the browser's compositing system obtains the image for the xr session. depthfar read only the distance, in meters, of the far clip plane from the viewer. the far clip plane is the plane which is parallel to the display beyond which renderi...
XRRigidTransform() - Web APIs
n object from the origin to the specified position and facing in the direction indicated by orientation. exceptions typeerror the value of the w coordinate in the specified position is not 1.0. examples in this example, the beginning of the animation of a scene is shown, starting with a request for a reference space of a given type, then shifting the coordinate system based on a transform before requesting the first animation frame. let animationframerequestid = 0; xrsession.requestreferencespace("local-floor") .then((refspace) => { xrreferencespace = refspace.getoffsetreferencespace( new xrrigidtransform(viewerposition, viewerorientation)); animationframerequestid = xrsession.requestanimationframe(drawframe); }); after requesting a reference space of type local-floor, the...
XRRigidTransform.matrix - Web APIs
rrigidtransform.matrix; value a float32array containing 16 entries which represents the 4x4 transform matrix which is described by the position and orientation properties. usage notes matrix format all 4x4 transform matrices used in webgl are stored in 16-element float32arrays. the values are stored into the array in column-major order; that is, each column is written into the array top-down before moving to the right one column and writing the next column into the array. thus, for an array [a0, a1, a2, ..., a13, a14, a15], the matrix looks like this: [a[0]a[4]a[8]a[12]a[1]a[5]a[9]a[13]a[2]a[6]a[10]a[14]a[3]a[7]a[11]a[15]]\begin{bmatrix} a[0] & a[4] & a[8] & a[12]\\ a[1] & a[5] & a[9] & a[13]\\ a[2] & a[6] & a[10] & a[14]\\ a[3] & a[7] & a[11] & a[15]\\ \end{bmatrix} the first time matrix...
XRRigidTransform - Web APIs
represent a matrix. xrrigidtransform.inverse read only returns a xrrigidtransform which is the inverse of this transform. that is, if applied to an object that had been previously transformed by the original transform, it will undo the transform and return the original object. usage notes when an xrrigidtransform is interpreted, the orientation is always applied to the affected object before the position is applied. example this code snippet creates an xrrigidtransform to specify the offset and orientation in relation to the current reference space to use when creating a new reference space. it then requests the first animation frame callback by calling the session's requestanimationframe() method. xrsession.requestreferencespace(refspacetype) .then((refspace) => { xrreferencesp...
XRSession.onselect - Web APIs
the onselect property of the xrsession object is the event handler for the select event, which is dispatched when a primary action is completed successfully by the user. this typically represents the pressing of a button or trigger, a hand gesture, or a spoken command. the select event is sent after tracking of the primary action begins, as announced by the selectstart event, and immediately before the tracking of the primary action ends, which is announced by the selectend event. to learn more about how webxr actions work, see inputs and input sources. syntax xrsession.onselect = selecthandlerfunction; value an event handler function to be invoked when the xrsession receives a select event. example this example handles select event which occur on the user's main hand (as given by a...
XRSession.updateRenderState() - Web APIs
the updaterenderstate() method of the xrsession interface of webxr api schedules changes to be applied to the active render state prior to rendering of the next frame. syntax xrsession.updaterenderstate(newstate) parameters newstate an object conforming to the xrrenderstateinit dictionary specifying the properties of the session's renderstate to update before rendering the next frame. the specified object may have any combination of the following fields. baselayer optional an xrwebgllayer object from which the webxr compositor will obtain imagery. this is null by default. depthfar optional a floating-point value specifying the distance in meters from the viewer to the far clip plane, which is a plane parallel to the display surface beyond which no further rendering wil...
XRSystem: requestSession() - Web APIs
sole.warn("'immersive-vr' isn't supported, or an error occurred activating vr!"); }); verifying webxr support and using a button to start vr mode the following example shows how to use both issessionsupported() and requestsession(). first, it checks to see if webxr is available by verifying the existence of navigator.xr. next, it calls issessionsupported(), passing it the desired session option before enabling controls for entering xr. adding controls is a necessary step because entering xr requires a user action. finally, the onbuttonclicked() method calls requestsession() using the same session option passed to issessionsupported(). if (navigator.xr) { navigator.xr.issessionsupported('immersive-vr') .then((issupported) => { if (issupported) { immersivebutton.addeventlistener('...
XRSystem - Web APIs
Web › API › XRSystem
checking to see if webxr is available by looking for the navigator.xr property. if it's found, we know webxr is present, so we proceed by establishing a handler for the button which the user can click to toggle immersive vr mode on and off. however, we don't yet know if the desired immersive mode is available. to determine this, we call issessionsupported(), passing it the desired session option before enabling the button, immersivebutton, which the user can then use to switch to immersive mode only if immersive vr mode is available. if immersive vr isn't available, the button is disabled to prevent its use. the onbuttonclicked() function checks to see if there's already a session running. if there isn't, we use requestsession() to start one and, once the returned promise resolves, we call a f...
XRWebGLLayer.getNativeFramebufferScaleFactor() static method - Web APIs
ons the browser needs to reduce image quality in order to improve performance to an acceptable level, it might choose to halve the resolution. in this case, the value returned by xrwebgllayer.getnativeframebufferscalefactor() will be 2.0. this method of dividing the frame buffer between views is shown in the following diagram. now the width and height of the frame buffer are 50% what they were before, resulting in a total frame buffer size of 1280 by 720 pixels, with each eye's half of the buffer being 640x720 pixels. now we can see the coordinates of each of the viewports representing these two views: since each eye gets half of the frame buffer, the result is that the left eye gets a 640x720 portion of the buffer with the viewport's x and y at 0, the width at 640, and the height set to 7...
XRWebGLLayerInit.antialias - Web APIs
ayerinit); let gllayer = new xrwebgllayer(xrsession, gl, { antialias: boolvalue }); value a boolean value which can be set to true to request anti-aliasing support in the new webgl rendering layer. if false, anti-aliasing is not desired. usage notes the state of anti-aliasing for the context after being created can be read from the xrwebgllayer property antialias. example in this example, before creating a new xrwebgllayer to use for rendering, the value of a user preference from a configuration interface is obtained using a function called getpreferencevalue() to determine whether the user has enabled or disabled anti-aliasing support; this is passed into the constructor. let options = { antialias: getpreferencevalue("antialiasing") }; let gllayer = new xrwebgllayer(xrsession, gl, o...
Web APIs
Web › API
udionodeoptions audioparam audioparamdescriptor audioparammap audioprocessingevent audioscheduledsourcenode audiotrack audiotracklist audioworklet audioworkletglobalscope audioworkletnode audioworkletnodeoptions audioworkletprocessor authenticatorassertionresponse authenticatorattestationresponse authenticatorresponse b baseaudiocontext basiccardrequest basiccardresponse batterymanager beforeinstallpromptevent beforeunloadevent biquadfilternode blob blobbuilder blobevent bluetooth bluetoothadvertisingdata bluetoothcharacteristicproperties bluetoothdevice bluetoothremotegattcharacteristic bluetoothremotegattdescriptor bluetoothremotegattserver bluetoothremotegattservice body broadcastchannel budgetservice budgetstate buffersource bytelengthqueuingstrategy by...
ARIA Screen Reader Implementors Guide - Accessibility
n the event occurs (earlier events come first). present items of the same politeness level in the order of what occurred first. atomic (aria-atomic="true") regions with multiple changes should not be presented twice with the same content. as a new event for an atomic region is added to the queue remove an earlier event for the same region. it is probably desirable to have at least a tiny timeout before presenting atomic region changes, in 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. i...
Using the alertdialog role - Accessibility
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 accessible role, name and optionally description before announcing the focused element. note: opinions may differ on how assistive technology should handle this technique. the information provided above is one of those opinions and therefore not normative. examples example 1: a basic alert dialog the code snippet below shows how to mark up an alert dialog that only provides a message and an ok button. <div role="alertdialog" aria-labelledby="dia...
Using the aria-invalid attribute - Accessibility
future expansion may add terms to the vocabulary used for this attribute. any value not in the current vocabulary should be treated as true. used in aria roles all elements of the base markup related aria techniques using the aria-required attribute using the alert role compatibility tbd: add support information for common ua an...
Using the aria-required attribute - Accessibility
this attribute can be used with any typical html form element; it is not limited to elements that have an aria role assigned. html5 now has the required attribute, but aria-required is still useful for user agents that do not yet support html5. value true or false (default: false) possible effects on user agents and assistive technology screen readers should announce the field as required. note that this attribute will not automatically change the presentation of the field. ...
Using the link role - Accessibility
to make it recognised as a link by assistive technology. this is a huge amount of work just to recreate something you've get for free using the <a> element, so you should really use that if possible. but this shows that it can be done. you should however note that there are still problems with this approach: it is very difficult to detect whether the target of the fake link has been visited before, and therefore use :visited styles (e.g. the default purple color for visited links). opening a page using the open() method counts as being a popup, and certain browsers may issue a warning when you try to activate it, or make you explicitly agree to allowing popups form the domain it exists on. html <h1>role="link" example</h1> <span data-href="https://mozilla.org" tabindex="0" id="link1" ...
ARIA: Mark role - Accessibility
semantically equivalent to the html <mark> element. if possible, you should use this element instead. examples in the following example we have a document section that has been commented. the commented section is marked up using <span role="mark">. <p>the last half of the song is a slow-rising crescendo that peaks at the <span role="mark" aria-details="thread-1">end of the guitar solo</span>, before fading away sharply.</p> <div role="comment" id="thread-1" data-author="chris"> <h3>chris said</h3> <p class="comment-text">i really think this moment could use more cowbell.</p> <p><time datetime="2019-03-30t19:29">march 30 2019, 19:29</time></p> </div> the related comment is marked up using an html structure wrapped with a <div> containing role="comment". to associate the comment with ...
ARIA: dialog role - Accessibility
hen the dialog appears on the screen, keyboard focus (whose control depends upon the dialogs purpose) should be moved to the default focusable control inside the dialog. for dialogs that only provide a basic message, it could be an "ok" button. for dialogs containing a form it could be the first field in the form. after the dialog is dismissed, keyboard focus should be moved back to where it was before it moved into the dialog. otherwise the focus can be dropped to the beginning of the page. for most dialogs, the expected behavior is that the dialog's tab order wraps, which means that when the user tabs through the focusable elements in the dialog, the first focusable element will be focused after the last one has been reached. in other words, the tab order should be contained within and by th...
ARIA - Accessibility
ve solution for testing full support, proxy assistive technology solutions aren't sufficient to fully guarantee functionality. tutorials introduction to aria a quick introduction to making dynamic content accessible with aria. see also the classic aria intro by gez lemon, from 2008. videos of screen readers using aria see both real and simplified examples from around the web, including "before" and "after" aria videos. using aria a practical guide for developers. it suggests what aria attributes to use on html elements. suggestions are based on implementation realities. simple aria enhancements enhancing page navigation with aria landmarks a nice intro to using aria landmarks to improve web page navigation for screen reader users. see also, aria landmark implementation notes an...
An overview of accessible web applications and widgets - Accessibility
r, 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, one element at a time. on fairly dense pages, a keyboard-only user often has to press the tab key dozens of times before accessing the needed section. 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.
Accessibility documentation index - Accessibility
what types of changes have occurred to an aria-live region, and which are relevant and should be announced. any change that is not relevant acts in the same manner it would if the aria-live attribute were set to off. 25 using the aria-required attribute aria, accessibility, needscontent the aria-required attribute is used to indicate that user input is required on an element before a form can be submitted. this attribute can be used with any typical html form element; it is not limited to elements that have an aria role assigned. 26 using the aria-valuemax attribute aria, accessibility the aria-valuemax attribute is used to define the maximum value allowed for a range widget such as a slider, spinbutton or progressbar. 27 using the aria-valu...
Mobile accessibility checklist - Accessibility
l heading</h3> aria landmark roles should be used to describe an app or document structure, such as banner, complementary, contentinfo, main, navigation, search. for touch events, at least one of the following must be true (wcag 2.1: pointer cancellation): the down-event should not be used to trigger any action the action is triggered on the up event and an option to abort the action before its completion is available or an option to undo the action after its completion the up-event will undo any action that was triggered on a down event it is essential to trigger the action on the down event. for example, playing a game or a piano application. touch targets must be large enough for the user to interact with (see the bbc mobile accessibility guidelines for useful touch t...
-moz-image-rect - CSS: Cascading Style Sheets
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. ...
:-moz-first-node - CSS: Cascading Style Sheets
note: any whitespace at the start of an element is ignored for the determination of :-moz-first-node. ...
::backdrop - CSS: Cascading Style Sheets
eneath the frontmost such element, and on top of the older full-screen elements. /* backdrop is only displayed when dialog is opened with dialog.showmodal() */ dialog::backdrop { background: rgba(255,0,0,.25); } all full-screen elements are placed in a last-in/first out (lifo) stack in the top layer, which is a special layer in the viewport which is always rendered last (and therefore on top) before drawing the viewport's contents to the screen. the ::backdrop pseudo-element makes it possible to obscure, style, or completely hide everything located below the element when it's the topmost one in the top layer. ::backdrop neither inherits from nor is inherited by any other elements. no restrictions are made on what properties apply to this pseudo-element. syntax ::backdrop examples stylin...
::first-letter (:first-letter) - CSS: Cascading Style Sheets
n 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 supported by browsers; see the browser compatibility table below.) a combination of the ::before pseudo-element and the content property may inject some text at the beginning of the element. in that case, ::first-letter will match the first letter of this generated content. css3 introduced the ::first-letter notation (with two colons) to distinguish pseudo-classes from pseudo-elements. browsers also accept :first-letter, introduced in css2. allowable properties only a small subset of c...
::part() - CSS: Cascading Style Sheets
Web › CSS › ::part
the ::part css pseudo-element represents any element within a shadow tree that has a matching part attribute. ...
:hover - CSS: Cascading Style Sheets
Web › CSS › :hover
user hovers over an element with the cursor (mouse pointer). /* selects any <a> element when "hovered" */ a:hover { color: orange; } styles defined by the :active pseudo-class will be overridden by any subsequent link-related pseudo-class (:link, :visited, or :active) that has at least equal specificity. to style links appropriately, put the :hover rule after the :link and :visited rules but before the :active one, as defined by the lvha-order: :link — :visited — :hover — :active. note: the :hover pseudo-class is problematic on touchscreens. depending on the browser, the :hover pseudo-class might never match, match only for a moment after touching an element, or continue to match even after the user has stopped touching and until the user touches another element. web developers shoul...
:link - CSS: Cascading Style Sheets
Web › CSS › :link
been visited. it matches every unvisited <a>, <area>, or <link> element that has an href attribute. /* selects any <a> that has not been visited yet */ a:link { color: red; } styles defined by the :link pseudo-class will be overridden by any subsequent link-related pseudo-class (:active, :hover, or :visited) that has at least equal specificity. to style links appropriately, put the :link rule before all other link-related rules, as defined by the lvha-order: :link — :visited — :hover — :active. note: use :any-link to select an element independent of whether it has been visited or not. syntax :link examples by default, most browsers apply a special color value to visited links. thus, the links in this example will probably have special font colors only before you visit them. (aft...
:required - CSS: Cascading Style Sheets
Web › CSS › :required
note: the :optional pseudo-class selects optional form fields. syntax :required examples see :invalid for an example. ...
:visited - CSS: Cascading Style Sheets
Web › CSS › :visited
ons, the styles that can be modified using this selector are very limited. /* selects any <a> that has been visited */ a:visited { color: green; } styles defined by the :visited pseudo-class will be overridden by any subsequent link-related pseudo-class (:link, :hover, or :active) that has at least equal specificity. to style links appropriately, put the :visited rule after the :link rule but before the :hover and :active rules, as defined by the lvha-order: :link — :visited — :hover — :active. styling restrictions for privacy reasons, browsers strictly limit which styles you can apply using this pseudo-class, and how they can be used: allowable css properties are color, background-color, border-color, border-bottom-color, border-left-color, border-right-color, border-top-color, c...
@charset - CSS: Cascading Style Sheets
Web › CSS › @charset
marked with preferred must be used. formal syntax @charset "<charset>"; examples valid and invalid charset declarations @charset "utf-8"; /* set the encoding of the style sheet to unicode utf-8 */ @charset 'iso-8859-15'; /* invalid, wrong quoting style used */ @charset "utf-8"; /* invalid, more than one space */ @charset "utf-8"; /* invalid, there is a character (a space) before the at-rule */ @charset utf-8; /* invalid, without ' or ", the charset is not a css <string> */ specifications specification status comment css level 2 (revision 1)the definition of '@charset' in that specification. recommendation initial definition browser compatibility the compatibility table on this page is generated from structured data. if...
@counter-style - CSS: Cascading Style Sheets
verting the integer value of a counter to a string representation. negative lets the author specify symbols to be appended or prepended to the counter representation if the value is negative. prefix specifies a symbol that should be prepended to the marker representation. prefixes are added to the representation in the final stage, so in the final representation of the counter, it comes before the negative sign. suffix specifies, similar to the prefix descriptor, a symbol that is appended to the marker representation. suffixes come after the marker representation. range defines the range of values over which the counter style is applicable. if a counter style is used to represent a counter value outside of its ranges, the counter style will drop back to its fallback style. ...
-webkit-transition - CSS: Cascading Style Sheets
use an @supports feature query instead. syntax @media (-webkit-transition) { /* css to use if transitions are supported */ } examples use @supports instead do not use the -webkit-transition media feature. instead, test for transition support using the css @supports at-rule, like this: @supports (transition: initial) { /* css to use if transitions are supported */ } obsolete example before this became obsolete, you could use -webkit-transition in your css like this: @media (-webkit-transition) { /* css to use if transitions are supported */ } specifications not part of any standard. ...
prefers-reduced-motion - CSS: Cascading Style Sheets
the prefers-reduced-motion css media feature is used to detect if the user has requested that the system minimize the amount of non-essential motion it uses. important: an embedded example at the bottom of this page has a scaling movement that may be problematic for some readers. readers with vestibular motion disorders may wish to enable the reduce motion feature on their device before viewing the animation. syntax no-preference indicates that the user has made no preference known to the system. reduce indicates that user has notified the system that they prefer an interface that removes or replaces the types of motion-based animation that trigger discomfort for those with vestibular motion disorders. user preferences for firefox, the reduce request is honoured if: in gt...
@viewport - CSS: Cascading Style Sheets
Web › CSS › @viewport
round @viewport's removal from the standards track. the @viewport css at-rule lets you configure the viewport through which the document is viewed. it's primarily used for mobile devices, but is also used by desktop browsers that support features like "snap to edge" (such as microsoft edge). lengths specified as percentages are calculated relative to the initial viewport, which is the viewport before any user agent or authored styles have had an opportunity to adjust the viewport. this is typically based on the size of the window on desktop browsers that aren't in full screen mode. on mobile devices (or desktop devices that are in full screen mode), the initial viewport is usually the portion of a device's screen that is available for application use. this may be either the full screen or th...
Attribute selectors - CSS: Cascading Style Sheets
alue] represents elements with an attribute name of attr whose value is prefixed (preceded) by value. [attr$=value] represents elements with an attribute name of attr whose value is suffixed (followed) by value. [attr*=value] represents elements with an attribute name of attr whose value contains at least one occurrence of value within the string. [attr operator value i] adding an i (or i) before the closing bracket causes the value to be compared case-insensitively (for characters within the ascii range). [attr operator value s] adding an s (or s) before the closing bracket causes the value to be compared case-sensitively (for characters within the ascii range). examples links css a { color: blue; } /* internal links, beginning with "#" */ a[href^="#"] { background-color: g...
CSS Animations tips and tricks - CSS: Cascading Style Sheets
ing the "changing" class that handles animation. in other words, we're removing the animation effect from the box. however, changes to the class list don't take effect until the style recomputation is complete and a refresh has occurred to reflect the change. to be sure that the styles are recalculated, we use window.requestanimationframe(), specifying a callback. our callback gets executed just before the next repaint of the document. the problem for us is that because it's before the repaint, the style recomputation hasn't actually happened yet! so... our callback cleverly calls requestanimationframe() a second time! this time, the callback is run before the next repaint, which is after the style recomputation has occurred. this callback adds the "changing" class back onto the box, so that t...
Border-image generator - CSS: Cascading Style Sheets
.span_5 { width: 40.7%; } .span_4 { width: 32.24%; } .span_3 { width: 23.78%; } .span_2 { width: 15.32%; } .span_1 { width: 6.86%; } /* sections * ========================================================================== */ .section { clear: both; padding: 0px; margin: 0px; } /* grouping * ========================================================================== */ .group: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 */ ...
Box alignment in Flexbox - CSS: Cascading Style Sheets
nt align-self align-items align-content there is no justify-self in flexbox on the main axis, flexbox deals with our content as a group. the amount of space required to lay out the items is calculated, and the leftover space is then available for distribution. the justify-content property controls how that leftover space is used. set justify-content: flex-end and the extra space is placed before the items, justify-content: space-around and it is placed either side of the item in that dimension, etc. this means that a justify-self property does not make sense in flexbox as we are always dealing with moving the entire group of items around. on the cross axis align-self makes sense as we potentially have additional space in the flex container in that dimension, in which a single item can ...
Handling Overflow in Multicol - CSS: Cascading Style Sheets
next set of columns. using vertical media queries one issue with multicol on the web is that, if your columns are taller than the viewport, the reader will need to scroll up and down to read, which is not good user experience. one way to avoid this is to only apply the column properties if you know you have enough height. in the example below we have used a min-height query to check the height before applying the column properties. in the final guide in this series we will see how multicol works with the fragmentation spec to give us control over how content breaks between columns. ...
Using multi-column layouts - CSS: Cascading Style Sheets
in some situations it is also useful to set the maximum height of the columns explicitly, and then lay out content starting at the first column and creating as many columns as necessary, possibly overflowing to the right. therefore, if the height is constrained, by setting the css height or max-height properties on a multi-column block, each column is allowed to grow to that height and no further before adding new column. this mode is also much more efficient for layout. column gaps there is a gap between columns. the recommended default is 1em. this size can be changed by applying the column-gap property to the multi-column block: example 6 html <div id="column_gap"> lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna ...
CSS Multi-column Layout - CSS: Cascading Style Sheets
refore the properties now defined in the css fragmentation specification are required in order to control how content breaks between columns. reference multiple-column layout properties column-count column-fill column-gap column-rule column-rule-color column-rule-style column-rule-width column-span column-width columns related css fragmentation properties break-after break-before break-inside orphans widows guides basic concepts of multicol an overview of the multiple-column layout specification styling columns how to use column rules and manage the spacing between columns. spanning and balancing how to make elements span across all columns and controlling the way columns are filled. handling overflow in multicol what happens when an item overflows the col...
Aligning Items in a Flex Container - CSS: Cascading Style Sheets
ue of align-content is space-between, which means that the available space is shared out between the flex lines, which are placed flush with the start and end of the container on the cross axis. try out the other values to see how the align-content property works. once again we can switch our flex-direction to column in order to see how this property behaves when we are working by column. as before, we need enough space in the cross axis to have some free space after displaying all of the items. note: the value space-evenly is not defined in the flexbox specification and is a later addition to the box alignment specification. browser support for this value is not as good as that of the values defined in the flexbox spec. see the documentation for justify-content on mdn for more detai...
Backwards Compatibility of Flexbox - CSS: Cascading Style Sheets
exbox is very well supported across modern browsers, however there are a few issues that you might run into. in this guide we will look at how well flexbox is supported in browsers, and look at some potential issues, resources and methods for creating workarounds and fallbacks. the history of flexbox as with all css specifications the flexbox specification went through a large number of changes before it became the 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 pre...
Basic concepts of flexbox - CSS: Cascading Style Sheets
, and also change the second to wrap and nowrap. properties applied to flex items to have more control over flex items we can target them directly. we do this by way of three properties: flex-grow flex-shrink flex-basis we will take a brief look at these properties in this overview, and you can gain a fuller understanding in the guide controlling ratios of flex items on the main axis. before we can make sense of these properties we need to consider the concept of available space. what we are doing when we change the value of these flex properties is to change the way that available space is distributed amongst our items. this concept of available space is also important when we come to look at aligning items. if we have three 100 pixel-wide items in a container which is 500 pixels w...
Ordering Flex Items - CSS: Cascading Style Sheets
tems laid out using flexbox. by changing which item has the class active assigned to it in the html, you can change which item displays first and therefore becomes full width at the top of the layout, with the other items displaying below it. the items are displayed in what is described in the specification as order-modified document order. the value of the order property is taken into account before the items are displayed. order also changes the paint order of the items; items with a lower value for order will be painted first and those with a higher value for order painted afterwards. the order property and accessibility use of the order property has exactly the same implications for accessibility as changing the direction with flex-direction. using order changes the order in which item...
Block and inline layout in normal flow - CSS: Cascading Style Sheets
ts as having a box, as with everything in css they do. these inline boxes are arranged one after the other. if there is not enough space in the containing block for all of the boxes a box can break onto a new line. the lines created are known as line boxes. in the following example, we have three inline boxes created by a paragraph with a <strong> element inside it. the boxes around the words before the <strong> element and after the <strong> element are referred to as anonymous boxes, boxes introduced to ensure that everything is wrapped in a box, but ones that we cannot target directly. the line box size in the block direction (so the height when working in english) is defined by the tallest box inside it. in the next example, i have made the <strong> element 300%; that content now define...
Flow Layout and Writing Modes - CSS: Cascading Style Sheets
d by the writing-mode, direction, and text-orientation properties. it is defined primarily in terms of its inline base direction and block flow direction.” the specification defines the inline base direction as the direction in which content is ordered on a line. this defines the start and end of the inline direction. the start is where sentences start and the end is where a line of text ends before it would begin to wrap onto a new line. the block flow direction is the direction in which boxes, for example paragraphs, stack in that writing mode. the css writing-mode property controls the block flow direction. if you want to change your page, or part of your page, to vertical-lr then you can set writing-mode: vertical-lr on the element and this will change the direction of the blocks and th...
CSS Flow Layout - CSS: Cascading Style Sheets
the flow is essentially a set of things that are all working together and know about each other in your layout. once something is taken out of flow it works independently. in normal flow, inline elements display in the inline direction, that is in the direction words are displayed in a sentence according to the writing mode of the document. block elements display one after the other, as paragraphs do in the writing mode of that document. ...
CSS Fragmentation - CSS: Cascading Style Sheets
displayed when it is broken (fragmented) across multiple pages, regions, or columns. fragmentation occurs when an inline box wraps onto multiple lines. it also occurs when a block spans more than one column inside a column layout container, or spans a page break when printed. each piece of the rendering for the element is called a fragment. reference box-decoration-break break-after break-before break-inside orphans widows specifications specification status comment css fragmentation module level 3 candidate recommendation initial definition. ...
Grid template areas - CSS: Cascading Style Sheets
good time to take a look at a couple of shorthands that are available for defining the grid and many things about it all in one line of css. these can quickly become difficult to read for other developers, or even your future self. however they are part of the specification and it is likely you will come across them in examples or in use by other developers, even if you choose not to use them. before using any shorthand it is worth remembering that shorthands not only enable the setting of many properties 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-te...
Realizing common layouts using CSS Grid Layout - CSS: Cascading Style Sheets
ue to build examples like the ones we have covered here. pick something that you normally build using your framework of choice, or using floats, and see if you can build it using grid. don’t forget to find examples that are impossible to build with current methods. that might mean taking inspiration from magazines or other non-web sources. grid layout opens up possibilities that we have not had before, we don’t need to be tied to the same old layouts to use it. for inspiration see the layout labs from jen simmons, she has been creating layouts based on a range of sources. for additional common layout patterns see grid by example, where there are many smaller examples of grid layout and also some larger ui patterns and full page layouts. ...
Logical properties for sizing - CSS: Cascading Style Sheets
er than a fixed size. try changing the example below to vertical-rl, as with the first example, to see the effect it has. i am using min-height in the first example and min-block-size in the second. max-width and max-height example finally you can use max-inline-size and max-block-size as logical replacements for max-width and max-height. try playing with the below example in the same way as before. logical keywords for resize the resize property sets whether or not an item can be resized and has physical values of horizontal and vertical. the resize property also has logical keyword values. using resize: inline allows resizing in the inline dimension and resize: block allow resizing in the block dimension. the keyword value of both for the resize property works whether you are thinkin...
CSS Paged Media - CSS: Cascading Style Sheets
Web › CSS › CSS Pages
css paged media is a module of css that defines how page switches are handled. ...
CSS Properties Reference - CSS: Cascading Style Sheets
ttom marginbottom margin-left marginleft margin-right marginright margin-top margintop overflow overflow padding padding padding-bottom paddingbottom padding-left paddingleft padding-right paddingright padding-top paddingtop page-break-after pagebreakafter page-break-before pagebreakbefore position position stroke-dasharray strokedasharray stroke-dashoffset strokedashoffset stroke-width strokewidth text-align textalign text-decoration textdecoration text-indent textindent text-transform texttransform top top vertical-align verticalalign ...
Overview of CSS Shapes - CSS: Cascading Style Sheets
around the circular shape rather than following the rectangle created by the box of the image. as in this level of the specification an element has to be floated in order to apply <basic-shape> to it; this has the side-effect of creating a simple fallback for many cases. if you do not have shapes support in the browser, the user will see content flowing around the sides of a rectangular box as before. if they do have shapes support then the visual display is enhanced. basic shapes the value circle(50%) is an example of a basic shape. the specification defines four <basic-shape> values, which are: inset() circle() ellipse() polygon() using the value inset() wraps text around a rectangular shape however you are able to add offset values, thus pulling the line boxes of any wrapping con...
CSS values and units - CSS: Cascading Style Sheets
, which are formatted similarly to a css property value. white space is allowed, but optional inside the parentheses. (but see notes regarding whitespace within pages for min(), max() and clamp() functions.) some legacy functional notations such as rgba() use commas, but generally commas are only used to separate items in a list. if a comma is used to separate arguments, white space is optional before and after the comma. specifications specification status comment css values and units module level 4 editor's draft adds the vi, vb, ic, cap, lh and rlh units. adds the min(), max() and clamp() functional notation adds toggle() css values and units module level 3 candidate recommendation adds calc(), ch, rem, vw, vw, vmin, vmax, q ...
Layout and the containing block - CSS: Cascading Style Sheets
cument, it generates a box for every element. each box is divided into four areas: content area padding area border area margin area many developers believe that the containing block of an element is always the content area of its parent, but that isn't necessarily true. let's investigate the factors that determine what an element's containing block is. effects of the containing block before learning what determines the containing block of an element, it's useful to know why it matters in the first place. the size and position of an element are often impacted by its containing block. percentage values that are applied to the width, height, padding, margin, and offset properties of an absolutely positioned element (i.e., which has its position set to absolute or fixed) are computed f...
Filter Effects - CSS: Cascading Style Sheets
filter effects is a module of css that defines a way of processing an element’s rendering before it is displayed in the document. reference properties backdrop-filter filter data types <filter-function> specifications specification status comment filter effects module level 1the definition of 'filter' in that specification. working draft initial definition. ...
Breadcrumb Navigation - CSS: Cascading Style Sheets
breadcrumb navigation helps the user to understand their location in the website by providing a breadcrumb trail back to the start page. requirements the items typically display inline with a separator to indicate a hierarchy between individual pages. recipe download this example note: the example above uses two selectors to insert content before every li except the first one. this could also be achieved using one selector only: .breadcrumb li:not(:first-child)::before { content: "→"; } this solution uses a more complex selector, but requires less rules. feel free to choose the solution that you prefer. choices made this pattern is laid out using a simple flex layout demonstrating how a line of css can give us our navigation. the separators are added using css generated co...
Center an element - CSS: Cascading Style Sheets
requirements to place an item into the center of another box horizontally and vertically. recipe download this example choices made to center one box inside another we make the containing box a flex container. then set align-items to center to perform centering on the block axis, and justify-content to center to perform centering on the inline axis. ...
Testing media queries programmatically - CSS: Cascading Style Sheets
to do this, use the window.matchmedia method. ...
Microsoft CSS extensions - CSS: Cascading Style Sheets
ll-rails -ms-scroll-snap-points-x -ms-scroll-snap-points-y -ms-scroll-snap-x -ms-scroll-snap-y -ms-scroll-translation -ms-text-autospace -ms-touch-select -ms-wrap-flow -ms-wrap-margin -ms-wrap-through zoom pseudo-elements ::-ms-browse ::-ms-check ::-ms-clear ::-ms-expand ::-ms-fill ::-ms-fill-lower ::-ms-fill-upper ::-ms-reveal ::-ms-thumb ::-ms-ticks-after ::-ms-ticks-before ::-ms-tooltip ::-ms-track ::-ms-value media features -ms-high-contrast css-related dom apis mscontentzoomfactor msgetpropertyenabled msgetregioncontent msrangecollection msregionoverflow ...
Paged media - CSS: Cascading Style Sheets
paged media properties control the presentation of content for print or any other media that splits content into discrete pages. it allows you to set page breaks, control printable area, style left and right pages differently, and control breaks inside elements. widely supported properties include: page-break-before page-break-after page-break-inside orphans widows @page ...
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. ...
Scaling of SVG backgrounds - CSS: Cascading Style Sheets
n't modified by constrain or cover, that specified size wins. if none of the above cases are met, the image is rendered at the same size as the background area. it's worth noting that the sizing algorithm only cares about the image's dimensions and proportions, or lack thereof. an svg image with fixed dimensions will be treated just like a raster image of the same size. source image examples before diving in to look at the results of using different kinds of source images and seeing how they look when used with background-size, it would be helpful to look at a few example source images that have different dimensions and sizing settings. in each case, we show what the source image looks like rendered in a 150x150 box, and provide a link to the svg source. dimensionless and proportionless ...
Syntax - CSS: Cascading Style Sheets
Web › CSS › Syntax
ties to specific values is the core function of the css language. a property and value pair is called a declaration, and any css engine calculates which declarations apply to every single element of a page in order to appropriately lay it out, and to style it. both properties and values are case-insensitive by default in css. the pair is separated by a colon, ':' (u+003a colon), and white spaces before, between, and after properties and values, but not necessarily inside, are ignored. there are more than 100 different properties in css and a nearly infinite number of different values. not all pairs of properties and values are allowed and each property defines what are the valid values. when a value is not valid for a given property, the declaration is deemed invalid and is wholly ignored by...
align-content - CSS: Cascading Style Sheets
each pair of adjacent items is the same. the first item is flush with the start edge of the alignment container in the cross axis, and the last item is flush with the end edge of the alignment container in the cross axis. space-around the items are evenly distributed within the alignment container along the cross axis. the spacing between each pair of adjacent items is the same. the empty space before the first and after the last item equals half of the space between each pair of adjacent items. space-evenly the items are evenly distributed within the alignment container along the cross axis. the spacing between each pair of adjacent items, the start edge and the first item, and the end edge and the last item, are all exactly the same. stretch if the combined size of the items along the cr...
animation-direction - CSS: Cascading Style Sheets
mine if a cycle is even or odd starts at one. 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 definition initial valuenormalapplies toall elements, ::before and ::after pseudo-elementsinheritednocomputed valueas specifiedanimation typediscrete formal syntax <single-animation-direction>#where <single-animation-direction> = normal | reverse | alternate | alternate-reverse examples see css animations for examples. specifications specification status comment css animationsthe definition of 'animation-direction' in that s...
animation-duration - CSS: Cascading Style Sheets
ementations may consider them as identical to 0s. 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 definition initial value0sapplies toall elements, ::before and ::after pseudo-elementsinheritednocomputed valueas specifiedanimation typediscrete formal syntax <time># examples see css animations for examples. specifications specification status comment css animationsthe definition of 'animation-duration' in that specification. working draft initial definition. ...
animation-name - CSS: Cascading Style Sheets
fier can't be none, unset, initial, or inherit. 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 definition initial valuenoneapplies toall elements, ::before and ::after pseudo-elementsinheritednocomputed valueas specifiedanimation typediscrete formal syntax [ none | <keyframes-name> ]#where <keyframes-name> = <custom-ident> | <string> examples see css animations for examples. specifications specification status comment css animationsthe definition of 'animation-name' in that specification. working draft initial...
animation-play-state - CSS: Cascading Style Sheets
paused the animation is currently paused. 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 definition initial valuerunningapplies toall elements, ::before and ::after pseudo-elementsinheritednocomputed valueas specifiedanimation typediscrete formal syntax <single-animation-play-state>#where <single-animation-play-state> = running | paused examples see css animations for examples. specifications specification status comment css animationsthe definition of 'animation-play-state' in that specification. working draf...
animation-timing-function - CSS: Cascading Style Sheets
p-start) step-end equal to steps(1, jump-end) 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. ...
attr() - CSS: Cascading Style Sheets
Web › CSS › attr
attr( <attr-name> <type-or-unit>? [, <attr-fallback> ]? ...
background-attachment - CSS: Cascading Style Sheets
n 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-size - CSS: Cascading Style Sheets
oportions. if it has no dimensions or only one dimension, it may or may not have proportions. css <gradient>s have no intrinsic dimensions or intrinsic proportions. background images created with the element() function use the intrinsic dimensions and proportions of the generating element. note: the behavior of <gradient>s changed in gecko 8.0 (firefox 8.0 / thunderbird 8.0 / seamonkey 2.5). before this, they were treated as images with no intrinsic dimensions, but with intrinsic proportions identical to that of the background positioning 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. th...
border-bottom - CSS: Cascading Style Sheets
s, border-bottom always sets the values of all of the properties that it can set, even if they are not specified. it sets those that are not specified to their default values. this means that ... border-bottom-style: dotted; border-bottom: thick green; ... is actually the same as ... border-bottom-style: dotted; border-bottom: none thick green; ... and the value of border-bottom-style given before border-bottom is ignored. since the default value of border-bottom-style is none, not specifying the border-style part results in no border. constituent properties this property is a shorthand for the following css properties: border-bottom-color border-bottom-style border-bottom-width syntax border-bottom: 1px; border-bottom: 2px dotted; border-bottom: medium dashed blue; the three v...
border-left - CSS: Cascading Style Sheets
nd properties, border-left always sets the values of all of the properties that it can set, even if they are not specified. it sets those that are not specified to their default values. this means that ... border-left-style: dotted; border-left: thick green; ... is actually the same as ... border-left-style: dotted; border-left: none thick green; ... and the value of border-left-style given before border-left is ignored. since the default value of border-left-style is none, not specifying the border-style part results in no border. constituent properties this property is a shorthand for the following css properties: border-left-color border-left-style border-left-width syntax border-left: 1px; border-left: 2px dotted; border-left: medium dashed green; the three values of the sh...
border-right - CSS: Cascading Style Sheets
perties, border-right always sets the values of all of the properties that it can set, even if they are not specified. it sets those that are not specified to their default values. this means that ... border-right-style: dotted; border-right: thick green; ... is actually the same as ... border-right-style: dotted; border-right: none thick green; ... and the value of border-right-style given before border-right is ignored. since the default value of border-right-style is none, not specifying the border-style part results in no border. constituent properties this property is a shorthand for the following css properties: border-right-color border-right-style border-right-width syntax border-right: 1px; border-right: 2px dotted; border-right: medium dashed green; the three values o...
border-top - CSS: Cascading Style Sheets
horthand properties, border-top always sets the values of all of the properties that it can set, even if they are not specified. it sets those that are not specified to their default values. this means that ... border-top-style: dotted; border-top: thick green; ... is actually the same as ... border-top-style: dotted; border-top: none thick green; ... and the value of border-top-style given before border-top is ignored. since the default value of border-top-style is none, not specifying the border-style part results in no border. constituent properties this property is a shorthand for the following css properties: border-top-color border-top-style border-top-width syntax border-top: 1px; border-top: 2px dotted; border-top: medium dashed green; the three values of the shorthand ...
box-pack - CSS: Cascading Style Sheets
Web › CSS › box-pack
values listed below. values start the box packs contents at the start, leaving any extra space at the end. center the box packs contents in the center, dividing any extra space equally between the start and the end. end the box packs contents at the end, leaving any extra space at the start. justify the space is divided evenly in-between each child, with none of the extra space placed before the first child or after the last child. if there is only one child, treat the value as if it were start. notes the edge of the box designated the start for packing purposes depends on the box's orientation and direction: normal reverse horizontal left right vertical top bottom the edge opposite to the start is designated the end. if the p...
clip-path - CSS: Cascading Style Sheets
Web › CSS › clip-path
{ margin: .5em; padding: .5em; background-color: #fff; overflow: hidden; text-align: center; flex: 1; } .note { background: #fff3d4; padding: 1em; margin: .5em .5em 0; font: .8em sans-serif; text-align: left; white-space: nowrap; } .note + .row .cell { margin-top: 0; } .container { display: inline-block; border: 1px dotted grey; position:relative; } .container:before { content: 'margin'; position: absolute; top: 2px; left: 2px; font: italic .6em sans-serif; } .viewbox { box-shadow: 1rem 1rem 0 #efefef inset, -1rem -1rem 0 #efefef inset; } .container.viewbox:after { content: 'viewbox'; position: absolute; left: 1.1rem; top: 1.1rem; font: italic .6em sans-serif; } .cell span { display: block; margin-bottom: .5em; } p { font-famil...
column-span - CSS: Cascading Style Sheets
all; /* global values */ column-span: inherit; column-span: initial; column-span: unset; an element that spans more than one column is called a spanning element. syntax the column-span property is specified as one of the keyword values listed below. values none the element does not span multiple columns. all the element spans across all columns. content in the normal flow that appears before the element is automatically balanced across all columns before the element appears. the element establishes a new block formatting context. formal definition initial valuenoneapplies toin-flow block-level elementsinheritednocomputed valueas specifiedanimation typediscrete formal syntax none | all examples making a heading span columns in this example, the heading is made to span across a...
counter() - CSS: Cascading Style Sheets
Web › CSS › counter
a counter has no visible effect by itself. the counter() function (and counters() function) is what makes it useful by returning developer defined strings (or images). note: the counter() function can be used with any css property, but support for properties other than content is experimental, and support for the type-or-unit parameter is sparse. check the browser compatibility table carefully before using this in production. syntax values <custom-ident> a name identifying the counter, which is the same case-sensitive name used for the counter-reset and counter-increment. the name cannot start with two dashes and can't be none, unset, initial, or inherit. <counter-style> a counter style name or symbols() function, where a counter style name is a numeric, alphabetic, or symbolic simp...
<display-outside> - CSS: Cascading Style Sheets
uter display type, which is essentially its role in flow layout. these keywords are used as values of the display property, and can be used for legacy purposes as a single keyword, or as defined in the level 3 specification alongside a value from the <display-inside> keywords. syntax valid <display-outside> values: block the element generates a block element box, generating line breaks both before and after the element when in the normal flow. inline the element generates one or more inline element boxes that do not generate line breaks before or after themselves. in normal flow, the next element will be on the same line if there is space run-in the element generates a run-in box. if the adjacent sibling of the element defined as display: run-in box is a block box, the run-in box bec...
display - CSS: Cascading Style Sheets
Web › CSS › display
.container { display: [ <display-outside> || <display-inside> ] | <display-listitem> | <display-internal> | <display-box> | <display-legacy> ; } outside <display-outside> these keywords specify the element’s outer display type, which is essentially its role in flow layout. valid <display-outside> values: block the element generates a block element box, generating line breaks both before and after the element when in the normal flow. inline the element generates one or more inline element boxes that do not generate line breaks before or after themselves. in normal flow, the next element will be on the same line if there is space run-in the element generates a run-in box. if the adjacent sibling of the element defined as display: run-in box is a block box, the run-in box bec...
<easing-function> - CSS: Cascading Style Sheets
the curve is not a function of time. */ cubic-bezier(2.45, 0.6, 4, 0.1) /* the two points must be defined, there is no default value. */ cubic-bezier(0.3, 2.1) /* abscissas must be in the [0, 1] range or the curve is not a function of time. */ cubic-bezier(-1.9, 0.3, -0.2, 2.1) steps() function examples these easing functions are valid: /* there is 5 treads, the last one happens right before the end of the animation. */ steps(5, end) /* a two-step staircase, the first one happening at the start of the animation. */ steps(2, start) /* the second parameter is optional. */ steps(2) these easing function are invalid: /* the first parameter must be an <integer> and cannot be a real value, even if it is equal to one. */ steps(2.0, jump-end) /* the amount of steps must be non-ne...
flex-direction - CSS: Cascading Style Sheets
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 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...
flex-wrap - CSS: Cascading Style Sheets
Web › CSS › flex-wrap
p; flex-wrap: wrap-reverse; /* global values */ flex-wrap: inherit; flex-wrap: initial; flex-wrap: unset; the flex-wrap property is specified as a single keyword chosen from the list of values below. values the following values are accepted: nowrap the flex items are laid out in a single line which may cause the flex container to overflow. the cross-start is either equivalent to start or before depending on the flex-direction value. this is the default value. wrap the flex items break into multiple lines. the cross-start is either equivalent to start or before depending flex-direction value and the cross-end is the opposite of the specified cross-start. wrap-reverse behaves the same as wrap but cross-start and cross-end are permuted. formal definition initial valuenowrapapplies t...
font-size-adjust - CSS: Cascading Style Sheets
79disabled full support 79disabled disabled from version 79: this feature is behind the enable experimental web platform features preference.firefox full support 40 full support 40 full support 3notes notes before firefox 40, font-size-adjust: 0 was incorrectly interpreted as font-size-adjust: none (bug 1144885). full support 1notes notes before firefox 3, font-size-adjust was supported on windows only.ie no support noopera full support 30disabled full supp...
font - CSS: Cascading Style Sheets
Web › CSS › font
14px arial; overflow: hidden; } .propinputcont { float: left; text-align: center; margin-right: 5px; width: 80px; } .setpropcont { float: left; margin-right: 5px; width: 120px; } .propinputs, .setpropcont { margin-bottom: 1em; } .curcss { border: none; border-bottom: 1px solid black; text-align: center; width: 80px; } .mandatory { border-bottom-color: red; } .cf:before, .cf:after { content: " "; display: table; } .cf:after { clear: both; } .tar { width: 40px; text-align: right; } .fontfamily { display: inline-block; } javascript var textareas = document.getelementsbyclassname("curcss"), shorttext = "", getcheckedvalue, setcss, getproperties, injectcss; getproperties = function () { shorttext = getcheckedvalue("font_s...
grid-area - CSS: Cascading Style Sheets
Web › CSS › grid-area
tom-ident> if there is a named line with the name '<custom-ident>-start'/'<custom-ident>-end', it contributes the first such line to the grid item’s placement. note: named grid areas automatically generate implicit named lines of this form, so specifying grid-area: foo; will choose the start/end edge of that named grid area (unless another line named foo-start/foo-end was explicitly specified before it). otherwise, this is treated as if the integer 1 had been specified along with the <custom-ident>. <integer> && <custom-ident>? contributes the nth grid line to the grid item’s placement. if a negative integer is given, it instead counts in reverse, starting from the end edge of the explicit grid. if a name is given as a <custom-ident>, only lines with that name are counted. if not en...
grid-column-end - CSS: Cascading Style Sheets
an, or a default span of 1. <custom-ident> if there is a named line with the name '<custom-ident>-end', it contributes the first such line to the grid item’s placement. note: named grid areas automatically generate implicit named lines of this form, so specifying grid-column-end: foo; will choose the end edge of that named grid area (unless another line named foo-end was explicitly specified before it). otherwise, this is treated as if the integer 1 had been specified along with the <custom-ident>. <integer> && <custom-ident>? contributes the nth grid line to the grid item’s placement. if a negative integer is given, it instead counts in reverse, starting from the end edge of the explicit grid. if a name is given as a <custom-ident>, only lines with that name are counted. if not en...
grid-column-start - CSS: Cascading Style Sheets
a default span of 1. <custom-ident> if there is a named line with the name <custom-ident>-start, it contributes the first such line to the grid item’s placement. note: named grid areas automatically generate implicit named lines of this form, so specifying grid-column-start: foo; will choose the start edge of that named grid area (unless another line named foo-start was explicitly specified before it). otherwise, this is treated as if the integer 1 had been specified along with the <custom-ident>. <integer> && <custom-ident>? contributes the nth grid line to the grid item’s placement. if a negative integer is given, it counts in reverse, starting from the end edge of the explicit grid. if a name is given as a <custom-ident>, only lines with that name are counted. if not enough lin...
grid-row-end - CSS: Cascading Style Sheets
span, or a default span of 1. <custom-ident> if there is a named line with the name '<custom-ident>-end', it contributes the first such line to the grid item’s placement. note: named grid areas automatically generate implicit named lines of this form, so specifying grid-row-end: foo; will choose the end edge of that named grid area (unless another line named foo-end was explicitly specified before it). otherwise, this is treated as if the integer 1 had been specified along with the <custom-ident>. the <custom-ident> cannot take the span value. <integer> && <custom-ident>? contributes the nth grid line to the grid item’s placement. if a negative integer is given, it instead counts in reverse, starting from the end edge of the explicit grid. if a name is given as a <custom-ident>,...
grid-row-start - CSS: Cascading Style Sheets
a default span of 1. <custom-ident> if there is a named line with the name '<custom-ident>-start', it contributes the first such line to the grid item’s placement. note: named grid areas automatically generate implicit named lines of this form, so specifying grid-row-start: foo; will choose the start edge of that named grid area (unless another line named foo-start was explicitly specified before it). otherwise, this is treated as if the integer 1 had been specified along with the <custom-ident>. <integer> && <custom-ident>? contributes the nth grid line to the grid item’s placement. if a negative integer is given, it instead counts in reverse, starting from the end edge of the explicit grid. if a name is given as a <custom-ident>, only lines with that name are counted. if not en...
grid-template - CSS: Cascading Style Sheets
columns'> sets grid-template-rows and grid-template-columns to the specified values, and sets grid-template-areas to none. [ <line-names>? <string> <track-size>? <line-names>? ]+ [ / <explicit-track-list> ]? sets grid-template-areas to the strings listed, grid-template-rows to the track sizes following each string (filling in auto for any missing sizes), and splicing in the named lines defined before/after each size, and grid-template-columns to the track listing specified after the slash (or none, if not specified). note: the repeat() function isn’t allowed in these track listings, as the tracks are intended to visually line up one-to-one with the rows/columns in the “ascii art”. note: the grid shorthand accepts the same syntax, but also resets the implicit grid properties to t...
image-orientation - CSS: Cascading Style Sheets
n image's orientation due to how it was shot or scanned, use a transform property with the rotate keyword to specify rotation. this includes any user-directed changes to the orientation of the image, or changes required for printing in portrait versus landscape orientation. if used in conjunction with other css properties, such as a <transform-function>, any image-orientation rotation is applied before any other transformations. formal definition initial value0degapplies toall elementsinheritedyescomputed valuean <angle>, rounded to the next quarter turn from 0deg and normalized, that is moduloing the value by 1turnanimation typediscrete formal syntax from-image | <angle> | [ <angle>? flip ] examples orienting image from image data css #image { image-orientation: from-image; /* can be...
image() - CSS: Cascading Style Sheets
right. displaying a section of the background image <div class="box">hover over me. what cursor do you see?</div> .box:hover { cursor: image("https://mdn.mozillademos.org/files/16411/sprite.png#xywh=32,64,16,16"); } when the user hovers over the box, the cursor will change to display the 16x16 px section of the sprite image, starting at x=32 and y=64. providing fallback images .help::before { content: image("try.webp", "try.svg", "try.gif"); } in this example, the browser will display an image as generated content before the content of the element with the class of help. the image displayed will be a webp image, if webp is supported. if not, the svg example will be shown. if svg is not supported, the gif version will display. putting color on top of a background image .qua...
justify-content - CSS: Cascading Style Sheets
tributed within the alignment container along the main axis. the spacing between each pair of adjacent items is the same. the first item is flush with the main-start edge, and the last item is flush with the main-end edge. space-around the items are evenly distributed within the alignment container along the main axis. the spacing between each pair of adjacent items is the same. the empty space before the first and after the last item equals half of the space between each pair of adjacent items. space-evenly the items are evenly distributed within the alignment container along the main axis. the spacing between each pair of adjacent items, the main-start edge and the first item, and the main-end edge and the last item, are all exactly the same. stretch if the combined size of the items a...
line-break - CSS: Cascading Style Sheets
or zwj character class or mandated by the word-break property. the different wrapping opportunities must not be prioritized. hyphenation is not applied. formal definition initial valueautoapplies toall elementsinheritedyescomputed valueas specifiedanimation typediscrete formal syntax auto | loose | normal | strict | anywhere examples setting text wrapping see whether the text is wrapped before "々", "ぁ" and "。". html <div lang="ja"> <p class="wrapbox auto">auto:<br>そこは湖のほとりで木々が輝いていた。<br>その景色に、美しいなぁと思わずつぶやいた。</p> <p class="wrapbox loose">loose:<br>そこは湖のほとりで木々が輝いていた。<br>その景色に、美しいなぁと思わずつぶやいた。</p> <p class="wrapbox normal">...
orphans - CSS: Cascading Style Sheets
Web › CSS › orphans
n, or column. /* <integer> values */ orphans: 2; orphans: 3; /* global values */ orphans: inherit; orphans: initial; orphans: unset; in typography, an orphan is the first line of a paragraph that appears alone at the bottom of a page. (the paragraph continues on a following page.) syntax values <integer> the minimum number of lines that can stay by themselves at the bottom of a fragment before a fragmentation break. the value must be positive. formal definition initial value2applies toblock container elementsinheritedyescomputed valueas specifiedanimation typediscrete formal syntax <integer> examples setting a minimum orphan size of three lines html <div> <p>this is the first paragraph containing some text.</p> <p>this is the second paragraph containing some more text than...
place-content - CSS: Cascading Style Sheets
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 baseline is end. space-around the items are evenly distributed within the alignment container. the spacing between each pair of adjacent items is the same. the empty space before the first and after the last item equals half of the space between each pair of adjacent items. space-evenly the items are evenly distributed within the alignment container. the spacing between each pair of adjacent items, the main-start edge and the first item, and the main-end edge and the last item, are all exactly the same. stretch if the combined size of the items is less than the size o...
quotes - CSS: Cascading Style Sheets
Web › CSS › quotes
second pair is for the first nested level, next pair for third level and so on. formal definition initial valuedepends on user agentapplies toall elementsinheritedyescomputed valueas specifiedanimation typediscrete formal syntax none | auto | [ <string> <string> ]+ examples basic quote marks html <q>to be or not to be. that's the question!</q> css q { quotes: '"' '"' "'" "'"; } q::before { content: open-quote; } q::after { content: close-quote; } result auto quotes for most browsers, the default value of quotes is auto (firefox 70+), or the browser otherwise had this default behavior (chromiums, safari, edge), so this example works without it being explicitly being set. html <div lang="fr"> <q>ceci est une citation française.</q> <div> <hr> <div lang="ru"> <q>Эт...
<ratio> - CSS: Cascading Style Sheets
Web › CSS › ratio
the first number represents the width, while the second represents the height. ...
shape-margin - CSS: Cascading Style Sheets
calc(); formal syntax <length-percentage>where <length-percentage> = <length> | <percentage> examples adding a margin to a polygon html <section> <div class="shape"></div> we are not quite sure of any one thing in biology; our knowledge of geology is relatively very slight, and the economic laws of society are uncertain to every one except some individual who attempts to set them forth; but before the world was fashioned the square on the hypotenuse was equal to the sum of the squares on the other two sides of a right triangle, and it will be so after this world is dead; and the inhabitant of mars, if he exists, probably knows its truth as we know it.</section> css section { max-width: 400px; } .shape { float: left; width: 150px; height: 150px; background-color: maroon; clip...
text-align-last - 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. ...
text-indent - 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. horizontal spacing is with respect to the left (or right, for right-to-left layout) edge of the containing block-level element's content box. ...
text-shadow - CSS: Cascading Style Sheets
t-x> and <offset-y> values. the third, optional, <length> value is the <blur-radius>. the<color> value is the shadow's color. when more than one shadow is given, shadows are applied front-to-back, with the first-specified shadow on top. this property applies to both ::first-line and ::first-letter pseudo-elements. values <color> optional. the color of the shadow. it can be specified either before or after the offset values. if unspecified, the color's value is left up to the user agent, so when consistency across browsers is desired you should define it explicitly. <offset-x> <offset-y> required. these <length> values specify the shadow's distance from the text. <offset-x> specifies the horizontal distance; a negative value places the shadow to the left of the text. <offset-y> specifies...
touch-action - CSS: Cascading Style Sheets
dling a touch gesture. by explicitly specifying which gestures should be handled by the browser, an application can supply its own behavior in pointermove and pointerup listeners for the remaining gestures. applications using touch events disable the browser handling of gestures by calling preventdefault(), but should also use touch-action to ensure the browser knows the intent of the application before any event listeners have been invoked. when a gesture is started, the browser intersects the touch-action values of the touched element and its ancestors, up to the one that implements the gesture (in other words, the first containing scrolling element). this means that in practice, touch-action is typically applied only to top-level elements which have some custom behavior, without needing to s...
rotate() - CSS: Cascading Style Sheets
otated</div> css div { width: 80px; height: 80px; background-color: skyblue; } .rotated { transform: rotate(45deg); /* equal to rotatez(45deg) */ background-color: pink; } result combining rotation with another transformation if you want apply multiple transformations to an element, be careful about the order in which you specify your transformations. ...
transition-duration - CSS: Cascading Style Sheets
duration: unset; values <time> is a <time> denoting the amount of time the transition from the old value of a property to the new value should take. a time of 0s indicates that no transition will happen, that is the switch between the two states will be instantaneous. a negative value for the time renders the declaration invalid. ...
transition-property - CSS: Cascading Style Sheets
sliding; /* global values */ transition-property: inherit; transition-property: initial; transition-property: unset; values none no properties will transition. all all properties that can transition will. <custom-ident> a string identifying the property to which a transition effect should be applied when its value changes. formal definition initial valueallapplies toall elements, ::before and ::after pseudo-elementsinheritednocomputed valueas specifiedanimation typediscrete formal syntax none | <single-transition-property>#where <single-transition-property> = all | <custom-ident> examples there are several examples of css transitions included in the main css transitions article. specifications specification status comment css transitionsthe defini...
transition-timing-function - CSS: Cascading Style Sheets
tain kinds of motion can be a trigger for vestibular disorders, epilepsy, and migraine and scotopic sensitivity. consider providing a mechanism for pausing or disabling animation, as well as using the reduced motion media query to create a complimentary experience for users who have expressed a preference for no animated experiences. ...
transition - CSS: Cascading Style Sheets
delay. see how things are handled when lists of property values aren't the same length. in short, extra transition descriptions beyond the number of properties actually being animated are ignored. ...
<url> - CSS: Cascading Style Sheets
Web › CSS › url
e narrower, initial definition. now, url() denotes only true <url>s. syntax the <url> data type is specified using the url() functional notation. it may be written without quotes, or surrounded by single or double quotes. relative urls are allowed, and are relative to the url of the stylesheet (not to the url of the web page). if you choose to write the url without quotes, use a backslash (\) before any parentheses, whitespace characters, single quotes (') and double quotes (") that are part of the url. <a_css_property>: url("http://mysite.example.com/mycursor.png") <a_css_property>: url('http://mysite.example.com/mycursor.png') <a_css_property>: url(http://mysite.example.com/mycursor.png) examples .topbanner { background: url("topbanner.png") #00d no-repeat fixed; } ul { list-styl...
user-select - CSS: Cascading Style Sheets
ited, 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. ...
CSS: Cascading Style Sheets
Web › CSS
with the language and its syntax, and got some basic experience with using it, its time to dive a bit deeper. this module looks at the cascade and inheritance, all the selector types we have available, units, sizing, styling backgrounds and borders, debugging, and lots more. the aim here is to provide you with a toolkit for writing competent css and help you understand all the essential theory, before moving on to more specific disciplines like text styling and css layout. styling text with the basics of the css language covered, the next css topic for you to concentrate on is styling text — one of the most common things you'll do with css. here we look at text styling fundamentals, including setting font, boldness, italics, line and letter spacing, drop shadows, and other text features.
set:leading() - EXSLT
Web › EXSLT › set › leading
syntax set:leading(nodeset1, nodeset2) parameters nodeset1 the node set to find nodes in that precede the first node in the second node set. nodeset2 the node set to compare against. returns a node-set containing the nodes from nodeset1 whose values precede the first node in nodeset2. ...
Sets (set) - EXSLT
Web › EXSLT › set
...
EXSLT
mespace the function is in, and then use the appropriate prefix when calling the function. for example, to use the regular expressions package: <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/xsl/transform" xmlns:regexp="http://exslt.org/regular-expressions"> <xsl:template match="/"> ... <xsl:value-of select="regexp:replace(/root/@value, 'before', 'gi', 'after')"/> ... </xsl:template> </xsl:stylesheet> common the exslt 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 namespa...
Getting Started - Developer guides
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. ...
Video player styling basics - Developer guides
creen apis. this follow-up article looks at how to style this custom player, including making it responsive. the example in action you can find the code for the updated, styled example on github, and view it live. preliminary modifications from the original example this section summarises the modifications that were made to the original video player example to make the styling task easier, before the bulk of the work was started. html markup there are a few changes that were made to the html markup shown in the previous article. the custom video controls and <progress> element are now contained within <div> elements, rather than residing inside unordered list items. the markup for the custom controls now looks as follows: <div id="video-controls" class="controls" data-state="hidden"> ...
Web Audio playbackRate explained - Developer guides
to see the effect. defaultplaybackrate and ratechange in addition to playbackrate, we also have a defaultplaybackrate property available, which lets us set the default playback rate: the playback rate to which the media resets; for example, if we change the source of the video, or (in some browsers) when an ended event is generated. so defaultplaybackrate allows us to set the playback rate before playing the media, while playbackrate allows us to change it during media playback. there is also an event available called ratechange, which fires every time the playbackrate changes. browser support chrome 20+ ✔ firefox 20+ ✔ ie 9+ ✔ safari 6+ ✔ opera 15+ ✔ mobile chrome (android) ✖ mobile firefox 24+ ✔ ie mobile ✖ mobile safari 6+ (ios) ✔ opera mobile ✖ no...
Creating a cross-browser video player - Developer guides
ascript. using the media api html5 comes with a javascript media api that allows developers access to and control of html5 media. this api will be used to make the custom control set defined above actually do something. in addition, the fullscreen button will use the fullscreen api, another w3c api that controls the ability of web browsers to show apps using your computer's full screen. setup before dealing with the individual buttons, a number of initialisation calls are required. to begin with, it's a good idea to first check if the browser actually supports the <video> element and to only setup the custom controls if it does. this is done by simply checking if a created <video> element supports the canplaytype() method, which any supported html5 <video> element should. var supportsvideo...
Media events - Developer guides
the playback state is changed to paused (paused property is true). play sent when the playback state is no longer paused, as a result of the play method, or the autoplay attribute. playing sent when the media has enough data to start playing, after the play event, but also when recovering from being stalled, when looping media restarts, and after seeked, if it was playing before seeking. progress sent periodically to inform interested parties of progress downloading the media. information about the current amount of the media that has been downloaded is available in the media element's buffered attribute. ratechange sent when the playback speed changes. seeked sent when a seek operation completes. seeking sent when a seek o...
Constraint validation - Developer guides
ntry zipfield.setcustomvalidity(constraints[country][1]); } } then we link it to the onchange event for the <select> and the oninput event for the <input>: window.onload = function () { document.getelementbyid("country").onchange = checkzip; document.getelementbyid("zip").oninput = checkzip; } you can see a live example of the postal code validation. limiting the size of a file before its upload another common constraint is to limit the size of a file to be uploaded. checking this on the client side before the file is transmitted to the server requires combining the constraint validation api, and especially the field.setcustomvalidity() method, with another javascript api, here the file api. here is the html part: <label for="fs">select a file smaller than 75 kb : </label> ...
Applying color to HTML elements using CSS - HTML: Hypertext Markup Language
maybe that's why color is one of the first things people often want to experiment with when learning to develop websites. with css, there are lots of ways to add color to your html elements to create just the look you want. this article is a primer introducing each of the ways css color can be used in html. fortunately, adding color to your html is actually really easy to do, and you can add color to nearly anything. ...
HTML attribute: required - HTML: Hypertext Markup Language
the required attribute is supported by text, search, url, tel, email, password, date, month, week, time, datetime-local, number, checkbox, radio, file, <input> types along with the <select> and <textarea> form control elements. if present on any of these input types and elements, the :required pseudo class will match. if the attribute is not included, the :optional pseudo class will match. the attribute is not supported or relevant to range and color, as both have default values. ...
Block-level elements - HTML: Hypertext Markup Language
html (hypertext markup language) elements historically were categorized as either "block-level" elements or "inline-level" elements. by default, a block-level element occupies the entire space of its parent element (container), thereby creating a "block." this article helps to explain what this means. browsers typically display the block-level element with a newline both before and after the element. you can visualize them as a stack of boxes. a block-level element always starts on a new line and takes up the full width available (stretches out to the left and right as far as it can). the following example demonstrates the block-level element's influence: block-level elements html <p>this paragraph is a block-level element; its background has been colored to display the paragraph...
<audio>: The Embed Audio element - HTML: Hypertext Markup Language
Web › HTML › Element › audio
me sets the current playback position to the given time and seeks the media to that position if the media is currently loaded. if the audio is being streamed, it's possible that the user agent may not be able to obtain some parts of the resource if that data has expired from the media buffer. other audio may have a media timeline that doesn't start at 0 seconds, so setting currenttime to a time before that would fail. for example, if the audio's media timeline starts at 12 hours, setting currenttime to 3600 would be an attempt to set the current playback position well before the beginning of the media, and would fail. the getstartdate() method can be used to determine the beginning point of the media timeline's reference frame. disableremoteplayback a boolean attribute used to disable th...
<base>: The Document Base URL element - HTML: Hypertext Markup Language
Web › HTML › Element › base
no closing tag. permitted parents a <head> that doesn't contain another <base> element. implicit aria role no corresponding role permitted aria roles no role permitted dom interface htmlbaseelement attributes this element's attributes include the global attributes. if either of the following attributes are specified, this element must come before other elements with attribute values of urls, such as <link>’s href attribute. href the base url to be used throughout the document for relative urls. absolute and relative urls are allowed. target a keyword or author-defined name of the default browsing context to show the results of navigation from <a>, <area>, or <form> elements without explicit target attributes. the following keywo...
<body>: The Document Body element - HTML: Hypertext Markup Language
Web › HTML › Element › body
erty on the element instead. leftmargin the margin of the left of the body. this method is non-conforming, use css margin-left property on the element instead. link color of text for unvisited hypertext links. this method is non-conforming, use css color property in conjunction with the :link pseudo-class instead. onafterprint function to call after the user has printed the document. onbeforeprint function to call when the user requests printing of the document. onbeforeunload function to call when the document is about to be unloaded. onblur function to call when the document loses focus. onerror function to call when the document fails to load properly. onfocus function to call when the document receives focus. onhashchange function to call when the fragment identifier pa...
<button>: The Button element - HTML: Hypertext Markup Language
Web › HTML › Element › button
when the form is submitted. notes a submit button with the attribute formaction set, but without an associated form does nothing. you have to set a form owner, either by wrapping it in a <form> or set the attribute form to the id of the form. <button> elements are much easier to style than <input> elements. you can add inner html content (think <i>, <br>, or even <img>), and use ::after and ::before pseudo-elements for complex rendering. if your buttons are not for submitting form data to a server, be sure to set their type attribute to button. otherwise they will try to submit form data and to load the (nonexistent) response, possibly destroying the current state of the document. example <button name="button">press me</button> accessibility concerns icon buttons buttons that only s...
<colgroup> - HTML: Hypertext Markup Language
Web › HTML › Element › colgroup
t: zero or more <col> element tag omission the start tag may be omitted, if it has a <col> element as its first child and if it is not preceded by a <colgroup> whose end tag has been omitted. the end tag may be omitted, if it is not followed by a space or a comment. permitted parents a <table> element. the <colgroup> must appear after any optional <caption> element but before any <thead>, <th>, <tbody>, <tfoot> and <tr> element. implicit aria role no corresponding role permitted aria roles no role permitted dom interface htmltablecolelement attributes this element's attributes include the global attributes. span this attribute contains a positive integer indicating the number of consecutive columns the <colgroup> eleme...
<details>: The Details disclosure element - HTML: Hypertext Markup Language
Web › HTML › Element › details
<details> element — are currently visible. the default, false, means the details are not visible. events in addition to the usual events supported by html elements, the <details> element supports the toggle event, which is dispatched to the <details> element whenever its state changes between open and closed. it is sent after the state is changed, although if the state changes multiple times before the browser can dispatch the event, the events are coalesced so that only one is sent. you can use an event listener for the toggle event to detect when the widget changes state: details.addeventlistener("toggle", event => { if (details.open) { /* the element was toggled open */ } else { /* the element was toggled closed */ } }); examples a simple disclosure example this exampl...
<dt>: The Description Term element - HTML: Hypertext Markup Language
Web › HTML › Element › dt
content categories none. permitted content flow content, but with no <header>, <footer>, sectioning content or heading content descendants. tag omission must have a start tag. the end tag may be omitted if this element is immediately followed by another <dt> or a <dd> element, or if there is no more content in the parent element. permitted parents before a <dt> or a <dd> element, inside a <dl> or (in whatwg html) a <div> that is inside a <dl>. implicit aria role term permitted aria roles listitem 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. example for a...
<iframe>: The Inline Frame element - HTML: Hypertext Markup Language
Web › HTML › Element › iframe
icy enforced for the embedded resource. see htmliframeelement.csp for details. height the height of the frame in css pixels. default is 150. importance the download priority of the resource in the <iframe>'s src attribute. allowed values: auto (default) no preference. the browser uses its own heuristics to decide the priority of the resource. high the resource should be downloaded before other lower-priority page resources. low the resource should be downloaded after other higher-priority page resources. loading indicates how the browser should load the iframe: eager: load the iframe immediately, regardless if it is outside the visible viewport (this is the default value). lazy: defer loading of the iframe until it reaches a calculated distance from the viewport...
<img>: The Image Embed element - HTML: Hypertext Markup Language
Web › HTML › Element › img
ge means. alt text is also displayed on the page if the image can't be loaded for some reason: for example, network errors, content blocking, or linkrot. there are many other attributes to achieve various purposes: referrer/cors control for security and privacy: see crossorigin and referrerpolicy. use both width and height to set the intrinsic size of the image, allowing it to take up space before it loads, to mitigate content layout shifts. responsive image hints with sizes and srcset (see also the <picture> element and our responsive images tutorial). supported image formats the html standard doesn't list what image formats to support, so each user agent supports different formats. a complete guide to image formats supported by web browsers is available. below is a list of the image ...
<input type="color"> - HTML: Hypertext Markup Language
Web › HTML › Element › input › color
you don't specify a value, the default is #000000, which is black. the value must be in seven-character hexadecimal notation, meaning the "#" character followed by two digits each representing red, green, and blue, like this: #rrggbb. if you have colors that are in any other format (such as css color names or css color functions such as rgb() or rgba()), you'll have to convert them to hexadecimal before setting the value. tracking color changes as is the case with other <input> types, there are two events that can be used to detect changes to the color value: input and change. input is fired on the <input> element every time the color changes. the change event is fired when the user dismisses the color picker. in both cases, you can determine the new value of the element by looking at its valu...
<input type="email"> - HTML: Hypertext Markup Language
Web › HTML › Element › input › email
fied, a list of e-mail addresses. the source for this interactive example is stored in a github repository. if 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 input value is automatically validated to ensure that it's either empty or a properly-formatted e-mail address (or list of addresses) before the form can be submitted. the :valid and :invalid css pseudo-classes are automatically applied as appropriate to visually denote whether the current value of the field is a valid e-mail address or not. on browsers that don't support inputs of type email, a email input falls back to being a standard text input. value a domstring representing an e-mail address, or empty even...
<input type="file"> - HTML: Hypertext Markup Language
Web › HTML › Element › input › file
next, let's walk through the javascript. in the first lines of script, we get references to the form input itself, and the <div> element with the class of .preview. next, we hide the <input> element — we do this because file inputs tend to be ugly, difficult to style, and inconsistent in their design across browsers. you can activate the input element by cli...
<input type="hidden"> - HTML: Hypertext Markup Language
Web › HTML › Element › input › hidden
no scripting is needed in the content to handle this. the output looks like this: note: you can also find the example on github (see the source code, and also see it running live). when submitted, the form data sent to the server...
<input type="month"> - HTML: Hypertext Markup Language
Web › HTML › Element › input › month
specifications specification status ...
<input type="number"> - HTML: Hypertext Markup Language
Web › HTML › Element › input › number
earlier on. since we want to accept a meter value in centimeters, we've set the step value to 0.01, so that values like 1.78 are not seen as invalid. we've also provided a placeholder for that input. we've hidden the feet and inches inputs initially using style="display: none;", so that meters is the default entry type. now, onto the css. this looks very similar to the validation styling we saw before; nothing remarkable here. div { margin-bottom: 10px; position: relative; } input[type="number"] { width: 100px; } input + span { padding-right: 30px; } input:invalid+span:after { position: absolute; content: '✖'; padding-left: 5px; } input:valid+span:after { position: absolute; content: '✓'; padding-left: 5px; } and finally, the javascript: let metersinputgroup = do...
<input type="search"> - HTML: Hypertext Markup Language
Web › HTML › Element › input › search
padding-left: 5px; position: absolute; } the technique also requires a <span> element to be placed after the form element, which acts as a holder for the icons. this was necessary because some input types on some browsers don't display icons placed directly after them very well. ...
<link>: The External Resource Link element - HTML: Hypertext Markup Language
Web › HTML › Element › link
preload examples you can find a number of <link rel="preload"> examples in preloading content with rel="preload". technical summary content categories metadata content. if itemprop is present: flow content and phrasing content. permitted content none, it is an empty element. tag omission as it is a void elemen...
<meta>: The Document-level Metadata element - HTML: Hypertext Markup Language
Web › HTML › Element › meta
uld redirect to another - only if the content attribute contains a positive integer followed by the string ';url=', and a valid url. accessibility concerns pages set with a refresh value run the risk of having the time interval being too short. people navigating with the aid of assistive technology such as a screen reader may be unable to read through and understand the page's content before being automatically redirected. the abrupt, unannounced updating of the page content may also be disorienting for people experiencing low vision conditions. mdn understanding wcag, guideline 2.1 explanations mdn understanding wcag, guideline 3.1 explanations understanding success criterion 2.2.1 | w3c understanding wcag 2.0 understanding success criterion 2.2.4 | w3c understa...
<param>: The Object Parameter element - HTML: Hypertext Markup Language
Web › HTML › Element › param
the html <param> element defines parameters for an <object> element. content categories none. permitted content none, it is an empty element. tag omission as it is a void element, the start tag must be present and the end tag must not be present. permitted parents an <object> before any flow content. implicit aria role no corresponding role permitted aria roles no role permitted dom interface htmlparamelement attributes this element includes the global attributes. name name of the parameter. value specifies the value of the parameter. deprecated attributes type only used if the valuetype is set to ref. specifies the mime type of values found at the uri specified by value. valuetyp...
<plaintext>: The Plain Text element (Deprecated) - HTML: Hypertext Markup Language
ent browsers inadvertently parsing content the element content as html. a monospaced font can be applied to any html element via a css font-family style with the monospace generic value. attributes this element has no other attributes than the global attributes common to all elements. dom interface this element implements the htmlelement interface. implementation note: in gecko 1.9.2 and before, firefox implements the interface htmlspanelement for this element. ...
<rp>: The Ruby Fallback Parenthesis element - HTML: Hypertext Markup Language
Web › HTML › Element › rp
thub.com/mdn/interactive-examples and send us a pull request. content categories none. permitted content text tag omission the end tag can be omitted if the element is immediately followed by an <rt> or another <rp> element, or if there is no more content in the parent element. permitted parents a <ruby> element. <rp> must be positioned immediately before or after an <rt> element. implicit aria role no corresponding role permitted aria roles any dom interface htmlelement attributes this element only includes the global attributes. usage notes ruby annotations are for showing pronunciation of east asian characters, like using japanese furigana or taiwanese bopomofo characters. the <rp> element is used...
<section>: The Generic Section element - HTML: Hypertext Markup Language
Web › HTML › Element › section
ent) as a child of the <section> element. if it makes sense to separately syndicate the content of a <section> element, use an <article> element instead. do not use the <section> element as a generic container; this is what <div> is for, especially when the sectioning is only for styling purposes. a rule of thumb is that a section should logically appear in the outline of a document. example before <div> <h1>heading</h1> <p>bunch of awesome content</p> </div> after <section> <h1>heading</h1> <p>bunch of awesome content</p> </section> specifications specification status comment html living standardthe definition of '<section>' in that specification. living standard html 5.1the definition of '<section>' in that specification. recomm...
<select>: The HTML Select element - HTML: Hypertext Markup Language
Web › HTML › Element › select
ur operating system) and then click multiple options to select/deselect them. warning: the mechanism for selecting multiple non-contiguous items via the keyboard described below currently only seems to work in firefox. also note: on macos, the ctrl + up and ctrl + down shortcuts conflict with the os default shortcuts for mission control and application windows, so you'll have to turn these off before it will work. keyboard users can select multiple contiguous items by: focusing on the <select> element (e.g. using tab). selecting an item at the top or bottom of the range they want to select using the up and down cursor keys to go up and down the options. holding down the shift key and then using the up and down cursor keys to increase or decrease the range of items selected. keyboard ...
<span> - HTML: Hypertext Markup Language
Web › HTML › Element › span
ntent, phrasing content. permitted content phrasing content. tag omission none, both the starting and ending tag are mandatory. permitted parents any element that accepts phrasing content, or any element that accepts flow content. implicit aria role no corresponding role permitted aria roles any dom interface htmlspanelement (before html5, the interface was htmlelement) attributes this element only includes the global attributes. example example 1 html <p><span>some text</span></p> result example 2 html <li><span> <a href="portfolio.html" target="_blank">see my portfolio</a> </span></li> css li span { background: gold; } result specifications specification status comment ...
<strong>: The Strong Importance element - HTML: Hypertext Markup Language
Web › HTML › Element › strong
ant distinction to make. while <em> is used to change the meaning of a sentence as spoken emphasis does ("i love carrots" vs. "i love carrots"), <strong> is used to give portions of a sentence added importance (e.g., "warning! this is very dangerous.") both <strong> and <em> can be nested to increase the relative degree of importance or stress emphasis, respectively. examples basic example <p>before proceeding, <strong>make sure you put on your safety goggles</strong>.</p> the resulting output: labeling warnings <p><strong>important:</strong> before proceeding, make sure you add plenty of butter.</p> this results in: specifications specification status comment html living standardthe definition of '<strong>' in that specification. living standard ...
<td>: The Table Data Cell element - HTML: Hypertext Markup Language
Web › HTML › Element › td
e 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. deprecated attributes abbr this attribute contains a short abbreviated description of the cell's content. some user-agents, such as speech readers, may present this description before the content itself. note: do not use this attribute as it is obsolete in the latest standard. alternatively, you can put the abbreviated description inside the cell and place the long content in the title attribute. align this enumerated attribute specifies how the cell content's horizontal alignment will be handled. possible values are: left: the content is aligned to the left of the ...
<th> - HTML: Hypertext Markup Language
Web › HTML › Element › th
ed parents a <tr> element. implicit aria role columnheader or rowheader permitted aria roles any dom interface htmltableheadercellelement attributes this element includes the global attributes. abbr this attribute contains a short abbreviated description of the cell's content. some user-agents, such as speech readers, may present this description before the content itself. colspan this attribute contains a non-negative integer value that indicates for how many columns the cell extends. its default value is 1. values higher than 1000 will be considered as incorrect and will be set to the default value (1). headers this attribute contains a list of space-separated strings, each corresponding to the id attribute of the <th> elements that apply ...
<thead>: The Table Head element - HTML: Hypertext Markup Language
Web › HTML › Element › thead
content categories none. permitted content zero or more <tr> elements. tag omission the start tag is mandatory. the end tag may be omitted if the <thead> element is immediately followed by a <tbody> or <tfoot> element. permitted parents a <table> element. the <thead> must appear after any <caption> or <colgroup> element, even implicitly defined, but before any <tbody>, <tfoot> and <tr> element. implicit aria role rowgroup permitted aria roles any dom interface htmltablesectionelement attributes this element includes the global attributes. deprecated attributes align in html 4, in html5 this enumerated attribute specifies how horizontal alignment of each cell content will be handled. possible valu...
<tr>: The Table Row element - HTML: Hypertext Markup Language
Web › HTML › Element › tr
<td>15.00</td> </tr> </table> the differences that matter here—for the purposes of discussing row and column spans—are in the first few lines of the code above. note the use of rowspan on to make the "name", "id", and "balance" headers occupy two rows instead of just one, and the use of colspan to make the "membership dates" header cell span across two columns. the css is unchanged from before. table { border: 1px solid black; } th, td { border: 1px solid black; } explicitly specifying table content groups before really getting into styling this table, let's take a moment to add row and column groups to help make our css easier. html the html is where the action is here, and the action is pretty simple. <table> <thead> <tr> <th rowspan="2">name</th> <th r...
<wbr> - HTML: Hypertext Markup Language
Web › HTML › Element › wbr
two lines, 123,456 and not 456,123. for the same reason, the <wbr> element does not introduce a hyphen at the line break point. to make a hyphen appear only at the end of a line, use the soft hyphen character entity (&shy;) instead. this element was first implemented in internet explorer 5.5 and was officially defined in html5. example the yahoo style guide recommends breaking a url before punctuation, to avoid leaving a punctuation mark at the end of the line, which the reader might mistake for the end of the url. <p>http://this<wbr>.is<wbr>.a<wbr>.really<wbr>.long<wbr>.example<wbr>.com/with<wbr>/deeper<wbr>/level<wbr>/pages<wbr>/deeper<wbr>/level<wbr>/pages<wbr>/deeper<wbr>/level<wbr>/pages<wbr>/deeper<wbr>/level<wbr>/pages<wbr>/deeper<wbr>/level<wbr>/pages</p> specification...
itemprop - HTML: Hypertext Markup Language
a url property element. the url property elements are the a, area, audio, embed, iframe, img, link, object, source, track, and video elements. name order names are unordered relative to each other, but if a particular name has multiple values, they do have a relative order. ...
tabindex - HTML: Hypertext Markup Language
o so by calling the focus() method. tabindex="0" means that the element should be focusable in sequential keyboard navigation, after any positive tabindex values and its order is defined by the document's source order. a positive value means the element should be focusable in sequential keyboard navigation, with its order defined by the value of the number. that is, tabindex="4" is focused before tabindex="5" and tabindex="0", but after tabindex="3". if multiple elements share the same positive tabindex value, their order relative to each other follows their position in the document source. the maximum value for tabindex is 32767. if not specified, it takes the default value 0. avoid using tabindex values greater than 0. doing so makes it difficult for people who rely on assistive te...
Preloading content with rel="preload" - HTML: Hypertext Markup Language
this ensures they are available earlier and are less likely to block the page's render, improving performance. this article provides a basic guide to how <link rel="preload"> works. ...
HTML: Hypertext Markup Language
Web › HTML
ty), which lets you configure the cors requests for the element's fetched data. preloading content with rel="preload" the preload value of the <link> element's rel attribute allows you to write declarative fetch requests in your html <head>, specifying resources that your pages will need very soon after loading, which you therefore want to start preloading early in the lifecycle of a page load, before the browser's main rendering machinery kicks in. this ensures that they are made available earlier and are less likely to block the page's first render, leading to performance improvements. this article provides a basic guide to how preload works. references html reference html consists of elements, each of which may be modified by some number of attributes. html documents are connected t...
Data URLs - HTTP
(|) character here common problems this section describes problems that commonly occur when creating and using data urls. data:text/html,lots of text...<p><a name%3d"bottom">bottom</a>?arg=val this represents an html resource whose contents are: lots of text...<p><a name="bottom">bottom</a>?arg=val syntax the format for data urls is very simple, but it's easy to forget to put a comma before the "data" segment, or to incorrectly encode the data into base64 format. formatting in html a data url provides a file within a file, which can potentially be very wide relative to the width of the enclosing document. as a url, the data should be formatable with whitespace (linefeed, tab, or spaces), but there are practical issues that arise when using base64 encoding. length limitations alt...
Identifying resources on the Web - HTTP
ys of the web, a path like this represented a physical file location on the web server. nowadays, it is mostly an abstraction handled by web servers without any physical reality. query ?key1=value1&key2=value2 are extra parameters provided to the web server. those parameters are a list of key/value pairs separated with the & symbol. the web server can use those parameters to do extra stuff before returning the resource to the user. each web server has its own rules regarding parameters, and the only reliable way to know how a specific web server is handling parameters is by asking the web server owner. fragment #somewhereinthedocument is an anchor to another part of the resource itself. an anchor represents a sort of "bookmark" inside the resource, giving the browser the directions...
HTTP conditional requests - HTTP
e first upload of a resource the first upload of a resource is an edge case of the previous. like any update of a resource, it is subject to a race condition if two clients try to perform at the similar times. to prevent this, conditional requests can be used: by adding if-none-match with the special value of '*', representing any etag. the request will succeed, only if the resource didn't exist before: if-none-match will only work with http/1.1 (and later) compliant servers. if unsure if the server will be compliant, you need first to issue a head request to the resource to check this. conclusion conditional requests are a key feature of http, and allow the building of efficient and complex applications. for caching or resuming downloads, the only work required for webmasters is to config...
Configuring servers for Ogg media - HTTP
f it can accept byte-range requests. it must return 206: partial content to all byte range requests; otherwise, browsers can't be sure you actually support byte range requests. your server must also return 206: partial content for the request range: bytes=0- as well. include regular key frames when the browser seeks through ogg media to a specified time, it has to seek to the nearest key frame before the seek target, then download and decode the video from there until the requested target time. the farther apart your key frames are, the longer this takes, so it's helpful to include key frames at regular intervals. by default, ffmpeg2theora uses one key frame every 64 frames (or about every 2 seconds at 30 frames per second), which works pretty well. note: of course, the more key frames you ...
Using HTTP cookies - HTTP
Web › HTTP › Cookies
omain or be ignored completely. as the application server checks for a specific cookie name only when determining if the user is authenticated or a csrf token is correct, this effectively acts as a defence measure against session fixation. on the application server, the web application must check for the full cookie name including the prefix—user agents do not strip the prefix from the cookie before sending it in a request's cookie header. for more information about cookie prefixes and the current state of browser support, see the prefixes section of the set-cookie reference article. javascript access using document.cookie new cookies can be created via javascript using the document.cookie property, and existing cookies can be accessed from javascript as well, if the httponly flag is not...
CSP: block-all-mixed-content - HTTP
the http content-security-policy (csp) block-all-mixed-content directive prevents loading any assets over http when the page uses https. all mixed content resource requests are blocked, including both active and passive mixed content. this also applies to <iframe> documents, ensuring the entire page is mixed content-free. the upgrade-insecure-requests directive is evaluated before block-all-mixed-content. if the former is set, the latter does nothing, so set one directive or the other – not both, unless you want to force https on older browsers that do not force it after a redirect to http. syntax content-security-policy: block-all-mixed-content; examples content-security-policy: block-all-mixed-content; <meta http-equiv="content-security-policy" content="block-all-mixed-content"> to...
CSP: report-uri - HTTP
further entries are added $email_address = 'admin@example.com'; $email_subject = 'content-security-policy violation'; // end configuration $current_domain = preg_replace('/www\./i', '', $_server['server_name']); $email_subject = $email_subject . ' on ' . $current_domain; http_response_code(204); // http 204 no content $json_data = file_get_contents('php://input'); // we pretty print the json before adding it to the log file if ($json_data = json_decode($json_data)) { $json_data = json_encode($json_data, json_pretty_print | json_unescaped_slashes); if (!file_exists($log_file)) { // send an email $message = "the following content-security-policy violation occurred on " . $current_domain . ":\n\n" . $json_data . "\n\nfurther cps violations will be logged to the f...
Expect-CT - HTTP
list 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 effect on https connections. the expect-ct will likely become obsolete in june 2021. since may 2018 new certificates are expected to support scts by default. certificates before march 2018 were allowed to have a lifetime of 39 months, those will all be expired in june 2021. header type response header forbidden header name yes syntax expect-ct: report-uri="<uri>", enforce, max-age=<age> directives max-age the number of seconds after reception of the expect-ct header field during which the user agent should r...
Expect - HTTP
Web › HTTP › Headers › Expect
ntax no other expectations except "100-continue" are specified currently. expect: 100-continue directives 100-continue informs recipients that the client is about to send a (presumably large) message body in this request and wishes to receive a 100 (continue) interim response. examples large message body a client sends a request with a expect header and waits for the server to respond before sending the message body. put /somewhere/fun http/1.1 host: origin.example.com content-type: video/h264 content-length: 1234567890987 expect: 100-continue the server now checks the request headers and may respond with a 100 (continue) response to instruct the client to go ahead and send the message body, or it will send a 417 (expectation failed) status if any of the expectations cannot be met...
Keep-Alive - HTTP
and a value separated by the equal sign ('='). the following identifiers are possible: timeout: indicating the minimum amount of time an idle connection has to be kept opened (in seconds). note that timeouts longer than the tcp timeout may be ignored if no keep-alive tcp message is set at the transport level. max: indicating the maximum number of requests that can be sent on this connection before closing it. unless 0, this value is ignored for non-pipelined connections as another request will be sent in the next response. an http pipeline can use it to limit the pipelining. examples a response containing a keep-alive header: http/1.1 200 ok connection: keep-alive content-encoding: gzip content-type: text/html; charset=utf-8 date: thu, 11 aug 2016 15:23:13 gmt keep-alive: timeout=5...
Pragma - HTTP
Web › HTTP › Headers › Pragma
mpatibility with http/1.0 clients. header type general header, but response behavior is not specified and thus implementation-specific. forbidden header name no cors-safelisted response header yes syntax pragma: no-cache directives no-cache same as cache-control: no-cache. forces caches to submit the request to the origin server for validation before releasing a cached copy. examples pragma: no-cache specifications specification title rfc 7234, section 5.4: pragma hypertext transfer protocol (http/1.1): caching ...
Retry-After - HTTP
the retry-after response http header indicates how long the user agent should wait before making a follow-up request. there are three main cases this header is used: when sent with a 503 (service unavailable) response, this indicates how long the service is expected to be unavailable. when sent with a 429 (too many requests) response, this indicates how long to wait before making a new request. when sent with a redirect response, such as 301 (moved permanently), this indicates the minimum time that the user agent is asked to wait before issuing the redirected request. header type response header forbidden header name no syntax retry-after: <http-date> retry-after: <delay-seconds> directives <http-date> a date after which to retry. see the date header...
Strict-Transport-Security - HTTP
s. includesubdomains optional if this optional parameter is specified, this rule applies to all of the site's subdomains as well. preload optional see preloading strict transport security for details. not part of the specification. description if a website accepts a connection through http and redirects to https, visitors may initially communicate with the non-encrypted version of the site before being redirected, if, for example, the visitor types http://www.foo.com/ or even just foo.com. this creates an opportunity for a man-in-the-middle attack. the redirect could be exploited to direct visitors to a malicious site instead of the secure version of the original site. the http strict transport security header informs the browser that it should never load a site using http and should aut...
Firefox user agent string reference - HTTP
me/59.0.3029.83 mobile safari/537.36 1.0 (webview tablet) mozilla/5.0 (linux; android 7.0) applewebkit/537.36 (khtml, like gecko) version/4.0 focus/1.0 chrome/59.0.3029.83 safari/537.36 6.0 (geckoview) mozilla/5.0 (android 7.0; mobile; rv:62.0) gecko/62.0 firefox/62.0 klar for android since version 4.1, klar for android uses the same ua string as focus for android. before version 4.1, it sent a klar/<version> product/version token. klar version (rendering engine) user agent string 1.0 (webview) mozilla/5.0 (linux; android 7.0) applewebkit/537.36 (khtml, like gecko) version/4.0 klar/1.0 chrome/58.0.3029.83 mobile safari/537.36 4.1+ (webview) mozilla/5.0 (linux; android 7.0) applewebkit/537.36 (khtml, like gecko) version/4.0 ...
Link prefetching FAQ - HTTP
y used on many sites. for this reason, link prefetching may not be appropriate for all content. however, it is possible to instruct mozilla to validate a prefetched document when the user follows a href to the prefetched document by specifying the cache-control: must-revalidate http response header. this header enables caching, but requires an if-modified-since or if-none-match validation request before the serving the document out of the browser's cache. as a server admin, can i distinguish prefetch requests from normal requests? yes, we send the following header along with each prefetch request: x-moz: prefetch of course, this request header is not at all standardized, and it may change in future mozilla releases. chrome uses "x-purpose: prefetch" or "purpose: prefetch" header. is there a...
Protocol upgrade mechanism - HTTP
"yes, i really mean to open a websocket connection." this header is automatically added by clients that choose to use it; it cannot be added using the xmlhttprequest.setrequestheader() method. sec-websocket-key: key key the key for this request to upgrade. the client adds this if it wishes to do so, and the server will include in the response a key of its own, which the client will validate before delivering the upgrade response to you. the server's response's sec-websocket-accept header will have a value computed based upon the specified key. sec-websocket-protocol the sec-websocket-protocol header specifies one or more websocket protocols that you wish to use, in order of preference. the first one that is supported by the server will be selected and returned by the server in a sec-we...
Redirections in HTTP - HTTP
u don't have control over the server. in that case, try a <meta> element with its http-equiv attribute set to refresh in the <head> of the page. when displaying the page, the browser will go to the indicated url. <head> <meta http-equiv="refresh" content="0; url=https://example.com/"> </head> the content attribute should start with a number indicating how many seconds the browser should wait before redirecting to the given url. always set it to 0 for accessibility compliance. obviously, this method only works with html, and cannot be used for images or other types of content. javascript redirections redirections in javascript are performed by setting a url string to the window.location property, loading the new page: window.location = "https://example.com/"; like html redirections, thi...
100 Continue - HTTP
Web › HTTP › Status › 100
the http 100 continue informational status response code indicates that everything so far is ok and that the client should continue with the request or ignore it if it is already finished. to have a server check the request's headers, a client must send expect: 100-continue as a header in its initial request and receive a 100 continue status code in response before sending the body. status 100 continue specifications specification title rfc 7231, section 6.2.1: 100 continue hypertext transfer protocol (http/1.1): semantics and content ...
201 Created - HTTP
Web › HTTP › Status › 201
the common use case of this status code is as the result of a post request. ...
429 Too Many Requests - HTTP
Web › HTTP › Status › 429
the http 429 too many requests response status code indicates the user has sent too many requests in a given amount of time ("rate limiting"). a retry-after header might be included to this response indicating how long to wait before making a new request. status 429 too many requests example http/1.1 429 too many requests content-type: text/html retry-after: 3600 specifications specification title rfc 6585, section 4: 429 too many requests additional http status codes ...
511 Network Authentication Required - HTTP
Web › HTTP › Status › 511
the http 511 network authentication required response status code indicates that the client needs to authenticate to gain network access. this status is not generated by origin servers, but by intercepting proxies that control access to the network. network operators sometimes require some authentication, acceptance of terms, or other user interaction before granting access (for example in an internet café or at an airport). they often identify clients who have not done so using their media access control (mac) addresses. status 511 network authentication required specifications specification title rfc 6585, section 6: 511 network authentication required additional http status codes ...
HTTP response status codes - HTTP
Web › HTTP › Status
id response. 503 service unavailable the server is not ready to handle the request. common causes are a server that is down for maintenance or that is overloaded. note that together with this response, a user-friendly page explaining the problem should be sent. this responses should be used for temporary conditions and the retry-after: http header should, if possible, contain the estimated time before the recovery of the service. the webmaster must also take care about the caching-related headers that are sent along with this response, as these temporary condition responses should usually not be cached. 504 gateway timeout this error response is given when the server is acting as a gateway and cannot get a response in time. 505 http version not supported the http version used in the reques...
Closures - JavaScript
er the following code example: function makefunc() { var name = 'mozilla'; function displayname() { alert(name); } return displayname; } var myfunc = makefunc(); myfunc(); running this code has exactly the same effect as the previous example of the init() function above. what's different (and interesting) is that the displayname() inner function is returned from the outer function before being executed. at first glance, it might seem unintuitive that this code still works. in some programming languages, the local variables within a function exist for just the duration of that function's execution. once makefunc() finishes executing, you might expect that the name variable would no longer be accessible. however, because the code still works as expected, this is obviously not the ...
Introduction - JavaScript
ello ' + yourname); } greetme('world'); /* end of your code */ })(); press cmd+enter or ctrl+enter (or click the run button) to watch it unfold in your browser! in the following pages, this guide introduces you to the javascript syntax and language features, so that you will be able to write more complex applications. but for now, remember to always include the (function(){"use strict"; before your code, and add })(); to the end of your code. you will learn what these mean, but for now they can be thought of as doing the following: massively improve performance. prevent stupid semantics in javascript that trip up beginners. prevent code snippets executed in the console from interacting with one-another (e.g., having something created in one console execution being used for a diffe...
Assertions - JavaScript
input. if the multiline flag is set to true, also matches immediately after a line break character. for example, /^a/ does not match the "a" in "an a", but does match the first "a" in "an a". this character has a different meaning when it appears at the start of a group. $ matches the end of input. if the multiline flag is set to true, also matches immediately before a line break character. for example, /t$/ does not match the "t" in "eater", but does match it in "eat". \b matches a word boundary. this is the position where a word character is not followed or preceded by another word-character, such as between a letter and a space. note that a matched word boundary is not included in the match. in other words, the length of a matched word...
Regular expression syntax cheatsheet - JavaScript
input. if the multiline flag is set to true, also matches immediately after a line break character. for example, /^a/ does not match the "a" in "an a", but does match the first "a" in "an a". this character has a different meaning when it appears at the start of a group. $ matches the end of input. if the multiline flag is set to true, also matches immediately before a line break character. for example, /t$/ does not match the "t" in "eater", but does match it in "eat". \b matches a word boundary. this is the position where a word character is not followed or preceded by another word-character, such as between a letter and a space. note that a matched word boundary is not included in the match. in other words, the length of a matched word...
Unicode property escapes - JavaScript
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 describe them exhaustively here but rather provide various examples rationale before es2018 there was no performance-efficient way to match characters from different sets based on scripts (like macedonian, greek, georgian etc.) or propertyname (like emoji etc) in javascript. check out tc39 proposal on unicode property escapes for more info. examples general categories general categories are used to classify unicode characters and subcategories are available to define a more pr...
Regular expressions - JavaScript
"b", you'd use /a\*b/ — the backslash "escapes" the "*", making it literal instead of special. similarly, if you're writing a regular expression literal and need to match a slash ("/"), you need to escape that (otherwise, it terminates the pattern). for instance, to search for the string "/example/" followed by one or more alphabetic characters, you'd use /\/example\/[a-z]+/i—the backslashes before each slash make them literal. to match a literal backslash, you need to escape the backslash. for instance, to match the string "c:\" where "c" can be any letter, you'd use /[a-z]:\\/ — the first backslash escapes the one after it, so the expression searches for a single literal backslash. if using the regexp constructor with a string literal, remember that the backslash is an escape in strin...
Text formatting - JavaScript
const germandictionary = new intl.collator('de-de-u-co-dict'); // as if sorting ["hochberg", "honigswald", "holzman"]: console.log(names.sort(germandictionary.compare).join(', ')); // logs "hochberg, holzman, hönigswald" for more information about the intl api, see also introducing the javascript internationalization api. « previousnext » ...
Working with objects - JavaScript
operties: for...in loops this method traverses all enumerable properties of an object and its prototype chain. object.keys(o) this method returns an array with all the own (not in the prototype chain) enumerable properties' names ("keys") of an object o. object.getownpropertynames(o) this method returns an array containing all own properties' names (enumerable or not) of an object o. before ecmascript 5, there was no native way to list all properties of an object. however, this can be achieved with the following function: function listallproperties(o) { var objecttoinspect; var result = []; for(objecttoinspect = o; objecttoinspect !== null; objecttoinspect = object.getprototypeof(objecttoinspect)) { result = result.concat( object.getownpropertyna...
Public class fields - JavaScript
ticfield.substaticfield) // expected output: "base static method output" public instance fields public instance fields exist on every created instance of a class. by declaring a public field, you can ensure the field is always present, and the class definition is more self-documenting. public instance fields are added with object.defineproperty() either at construction time in the base class (before the constructor body runs), or just after super() returns in a subclass. class classwithinstancefield { instancefield = 'instance field' } const instance = new classwithinstancefield() console.log(instance.instancefield) // expected output: "instance field" fields without initializers are initialized to undefined. class classwithinstancefield { instancefield } const instance = new classw...
extends - JavaScript
ng extends the first example creates a class called square from a class called polygon. this example is extracted from this live demo (source). class square extends polygon { constructor(length) { // here, it calls the parent class' constructor with lengths // provided for the polygon's width and height super(length, length); // note: in derived classes, super() must be called before you // can use 'this'. leaving this out will cause a reference error. this.name = 'square'; } get area() { return this.height * this.width; } } using extends with built-in objects this example extends the built-in date object. this example is extracted from this live demo (source). class mydate extends date { getformatteddate() { var months = ['jan', 'feb', 'mar', 'ap...
Classes - JavaScript
peak() { console.log(`${this.name} makes a noise.`); } } class dog extends animal { constructor(name) { super(name); // call the super class constructor and pass in the name parameter } speak() { console.log(`${this.name} barks.`); } } let d = new dog('mitzie'); d.speak(); // mitzie barks. if there is a constructor present in the subclass, it needs to first call super() before using "this". one may also extend traditional function-based "classes": function animal (name) { this.name = name; } animal.prototype.speak = function () { console.log(`${this.name} makes a noise.`); } class dog extends animal { speak() { console.log(`${this.name} barks.`); } } let d = new dog('mitzie'); d.speak(); // mitzie barks. // for similar methods, the child's method take...
ReferenceError: deprecated caller or arguments usage - JavaScript
e function was called from the top!'; } else { return 'this function\'s caller was ' + myfunc.caller; } } myfunc(); // warning: referenceerror: deprecated caller usage // "the function was called from the top!" function.arguments function.arguments is deprecated (see the reference article for more information). 'use strict'; function f(n) { g(n - 1); } function g(n) { console.log('before: ' + g.arguments[0]); if (n > 0) { f(n); } console.log('after: ' + g.arguments[0]); } f(2); console.log('returned: ' + g.arguments); // warning: referenceerror: deprecated arguments usage ...
RangeError: invalid array length - JavaScript
ngth limited? the length property of an array or an arraybuffer is represented with an unsigned 32-bit integer, that can only store values which are in the range from 0 to 232-1. if you are creating an array, using the constructor, you probably want to use the literal notation instead, as the first argument is interpreted as the length of the array. otherwise, you might want to clamp the length before setting the length property, or using it as argument of the constructor. examples invalid cases new array(math.pow(2, 40)) new array(-1) new arraybuffer(math.pow(2, 32)) new arraybuffer(-1) let a = []; a.length = a.length - 1; // set -1 to the length property let b = new array(math.pow(2, 32) - 1); b.length = b.length + 1; // set 2^32 to the length property valid cases [ m...
ReferenceError: "x" is not defined - JavaScript
" occurs when there is a non-existent variable referenced somewhere. message referenceerror: "x" is not defined error type referenceerror. what went wrong? there is a non-existent variable referenced somewhere. this variable needs to be declared, or you need to make sure it is available in your current script or scope. note: when loading a library (such as jquery), make sure it is loaded before you access library variables, such as "$". put the <script> tag that loads the library before your code that uses it. examples variable not declared foo.substring(1); // referenceerror: foo is not defined the "foo" variable isn't defined anywhere. it needs to be some string, so that the string.prototype.substring() method will work. var foo = 'bar'; foo.substring(1); // "ar" wrong scope ...
TypeError: Reduce of empty array with no initial value - JavaScript
ovide an initialvalue as the neutral element of the operator, such as 0 for the addition, 1 for a multiplication, or an empty string for a concatenation. var ints = [0, -1, -2, -3, -4, -5]; ints.filter(x => x > 0) // removes all elements .reduce((x, y) => x + y, 0) // the initial value is the neutral element of the addition another way would be two to handle the empty case, either before calling reduce, or in the callback after adding an unexpected dummy initial value. var names = document.getelementsbyclassname("names"); var name_list1 = ""; if (names1.length >= 1) name_list1 = array.prototype.reduce.call(names, (acc, name) => acc + ", " + name); // name_list1 == "" when names is empty. var name_list2 = array.prototype.reduce.call(names, (acc, name) => { if (acc == "") //...
ReferenceError: assignment to undeclared variable "x" - JavaScript
ord. there are some differences between declared and undeclared variables, which might lead to unexpected results and that's why javascript presents an error in strict mode. three things to note about declared and undeclared variables: declared variables are constrained in the execution context in which they are declared. undeclared variables are always global. declared variables are created before any code is executed. undeclared variables do not exist until the code assigning to them is executed. declared variables are a non-configurable property of their execution context (function or global). undeclared variables are configurable (e.g. can be deleted). for more details and examples, see the var reference page. errors about undeclared variable assignments occur in strict mode code on...
Arrow function expressions - JavaScript
foobarx); // [8, 6, 7, 9] // this destructuring parameter assignment can also be written as seen below. however, note that in // this example we are not assigning `length` value to the made up property. instead, the literal name // itself of the variable `length` is used as the property we want to retrieve from the object. elements.map(({ length }) => length); // [8, 6, 7, 9] no separate this before arrow functions, every new function defined its own this value based on how the function was called: a new object in the case of a constructor. undefined in strict mode function calls. the base object if the function was called as an "object method". etc. this proved to be less than ideal with an object-oriented style of programming. function person() { // the person() constructor defi...
Method definitions - JavaScript
n ecmascript 2015. given the following code: const obj = { foo: function() { // ... }, bar: function() { // ... } } you are now able to shorten this to: const obj = { foo() { // ... }, bar() { // ... } } generator methods generator methods can be defined using the shorthand syntax as well. when doing so: the asterisk (*) in the shorthand syntax must be before the generator property name. (that is, * g(){} will work, but g *(){} will not.) non-generator method definitions cannot contain the yield keyword. this means that legacy generator functions won't work either, and will throw a syntaxerror. always use yield in conjunction with the asterisk (*). // using a named property const obj2 = { g: function* () { let index = 0 while (true) ...
arguments.callee - JavaScript
wn function, it is not possible to inline f. basically it means that any call site that may have been trivially inlinable accumulates a large number of guards: function f(a, b, c, d, e) { return a ? b * c : d * e; } if the javascript interpreter cannot guarantee that all the provided arguments are numbers at the point that the call is made, it needs to either insert checks for all the arguments before the inlined code, or it cannot inline the function. now in this particular case a smart interpreter should be able to rearrange the checks to be more optimal and not check any values that would not be used. however in many cases that's just not possible and therefore it becomes impossible to inline. examples using arguments.callee in an anonymous recursive function a recursive function must be...
Rest parameters - JavaScript
; the arguments object is not a real array, while rest parameters are array instances, meaning methods like sort, map, foreach or pop can be applied on it directly; the arguments object has additional functionality specific to itself (like the callee property). ...
Array.prototype.every() - JavaScript
rsed. if a thisarg parameter is provided to every, it will be used as callback's this value. otherwise, the value undefined will be used as its this value. the this value ultimately observable by callback is determined according to the usual rules for determining the this seen by a function. every does not mutate the array on which it is called. the range of elements processed by every is set before the first invocation of callback. therefore, callback will not run on elements that are appended to the array after the call to every begins. if existing elements of the array are changed, their value as passed to callback will be the value at the time every visits them. elements that are deleted are not visited. every acts like the "for all" quantifier in mathematics. in particular, for an empt...
Array.prototype.find() - JavaScript
icient for sparse arrays, compared to methods that only visit assigned values. if a thisarg parameter is provided to find, it will be used as the this value inside each invocation of the callback. if it is not provided, then undefined is used. the find method does not mutate the array on which it is called, but the function provided to callback can. if so, the elements processed by find are set before the first invocation of callback. therefore: callback will not visit any elements added to the array after the call to find begins. if an existing, yet-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...
Array.prototype.findIndex() - JavaScript
s run even for indexes with unassigned values. 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 passed to findindex(), it will be used as the this inside each invocation of the callback. if it is not provided, then undefined is used. the range of elements processed by findindex() is set before the first invocation of callback. callback will not process the elements appended to the array after the call to findindex() begins. if an existing, unvisited element of the array is changed by callback, its value passed to the callback will be the value at the time findindex() visits the element's index. elements that are deleted are still visited. polyfill // https://tc39.github.io/ecma262/#...
Array.isArray() - JavaScript
rs value the value to be checked. return value true if the value is an array; otherwise, false. description if the value is an array, true is returned; otherwise, false is. see the article “determining with absolute accuracy whether or not a javascript object is an array” for more details. given a typedarray instance, false is always returned. polyfill running the following code before any other code will create array.isarray() if it's not natively available. if (!array.isarray) { array.isarray = function(arg) { return object.prototype.tostring.call(arg) === '[object array]'; }; } examples using array.isarray // all following calls return true array.isarray([]); array.isarray([1]); array.isarray(new array()); array.isarray(new array('a', 'b', 'c', 'd')); array.isar...
Array.prototype.map() - JavaScript
is provided, it will be used as callback's this value. otherwise, the value undefined will be used as its this value. the this value ultimately observable by callback is determined according to the usual rules for determining the this seen by a function. map does not mutate the array on which it is called (although callback, if invoked, may do so). the range of elements processed by map is set before the first invocation of callback. elements which are appended to the array after the call to map begins will not be visited by callback. if existing elements of the array are changed, their value as passed to callback will be the value at the time map visits them. elements that are deleted after the call to map begins and before being visited are not visited. due to the algorithm defined in the ...
Array.of() - JavaScript
7 empty slots array(1, 2, 3); // [1, 2, 3] syntax array.of(element0[, element1[, ...[, elementn]]]) parameters elementn elements used to create the array. return value a new array instance. description this function is part of the ecmascript 2015 standard. for more information, see: array.of() array.from() proposal array.of() polyfill polyfill running the following code before any other code will create array.of() if it's not natively available. if (!array.of) { array.of = function() { return array.prototype.slice.call(arguments); // or let vals = []; for(let prop in arguments){ vals.push(arguments[prop]); } return vals; } } examples using array.of array.of(1); // [1] array.of(1, 2, 3); // [1, 2, 3] array.of(undefined)...
Array.prototype.slice() - JavaScript
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. if start is undefined, slice starts from the index 0. if start is greater than the index range of the sequence, an empty array is returned. end optional zero-based index before which to end extraction. slice extracts up to but not including end. for example, slice(1,4) extracts the second element through the fourth element (elements indexed 1, 2, and 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...
Array.prototype.some() - JavaScript
if a thisarg parameter is provided to some(), it will be used as the callback's this value. otherwise, the value undefined will be used as its this value. the this value ultimately observable by callback is determined according to the usual rules for determining the this seen by a function. some() does not mutate the array on which it is called. the range of elements processed by some() is set before the first invocation of callback. elements appended to the array after the call to some() begins will not be visited by callback. if an existing, unvisited element of the array is changed by callback, its value passed to the 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...
ArrayBuffer.prototype.slice() - JavaScript
nclusive, up to end, exclusive. the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax arraybuffer.slice(begin[, end]) parameters begin zero-based byte index at which to begin slicing. end optional byte index before which to end slicing. if end is unspecified, the new arraybuffer contains all bytes from begin to the end of this arraybuffer. return value a new arraybuffer object. description the slice() method copies up to, but not including, the byte indicated by the end parameter. if either begin or end is negative, it refers to an index from the end of the array, as opposed to from the beginning. the...
Atomics - JavaScript
structor. you cannot use it with a new operator or invoke the atomics object as a function. all properties and methods of atomics are static (as is the case with the math object, for example). atomic operations when memory is shared, multiple threads can read and write the same data in memory. atomic operations make sure that predictable values are written and read, that operations are finished before the next operation starts and that operations are not interrupted. wait and notify the wait() and notify() methods are modeled on linux futexes ("fast user-space mutex") and provide ways for waiting until a certain condition becomes true and are typically used as blocking constructs. static methods atomics.add() adds the provided value to the existing value at the specified index of the ar...
BigInt64Array() constructor - JavaScript
length argument, an internal array buffer is created in memory, of size length multiplied by bytes_per_element bytes, containing zeros. typedarray when called with a typedarray argument, which can be an object of any of the typed array types (such as int32array), the typedarray gets copied into a new typed array. each value in typedarray is converted to the corresponding type of the constructor before being copied into the new array. the length of the new typed array will be same as the length of the typedarray argument. object when called with an object argument, a new typed array is created as if by the typedarray.from() method. buffer, byteoffset, length when called with a buffer, and optionally a byteoffset and a length argument, a new typed array view is created that views the specifi...
BigUint64Array() constructor - JavaScript
length argument, an internal array buffer is created in memory, of size length multiplied by bytes_per_element bytes, containing zeros. typedarray when called with a typedarray argument, which can be an object of any of the typed array types (such as int32array), the typedarray gets copied into a new typed array. each value in typedarray is converted to the corresponding type of the constructor before being copied into the new array. the length of the new typed array will be same as the length of the typedarray argument. object when called with an object argument, a new typed array is created as if by the typedarray.from() method. buffer, byteoffset, length when called with a buffer, and optionally a byteoffset and a length argument, a new typed array view is created that views the specifi...
Date.prototype.getYear() - JavaScript
ar() is 100 or greater. for example, if the year is 2026, getyear() returns 126. for years between and including 1900 and 1999, the value returned by getyear() is between 0 and 99. for example, if the year is 1976, getyear() returns 76. for years less than 1900, the value returned by getyear() is less than 0. for example, if the year is 1800, getyear() returns -100. to take into account years before and after 2000, you should use getfullyear() instead of getyear() so that the year is specified in full. backward compatibility behavior in javascript 1.2 and earlier the getyear() method returns either a 2-digit or 4-digit year: for years between and including 1900 and 1999, the value returned by getyear() is the year minus 1900. for example, if the year is 1976, the value returned is 76. ...
Date.prototype.setDate() - JavaScript
the dayvalue is outside of the range of date values for the month, setdate() will update the date object accordingly. for example, if 0 is provided for dayvalue, the date will be set to the last day of the previous month. if a negative number is provided for dayvalue, the date will be set counting backwards from the last day of the previous month. -1 would result in the date being set to 1 day before the last day of the previous month. examples using setdate() var thebigday = new date(1962, 6, 7); // 1962-07-07 (7th of july 1962) thebigday.setdate(24); // 1962-07-24 (24th of july 1962) thebigday.setdate(32); // 1962-08-01 (1st of august 1962) thebigday.setdate(22); // 1962-08-22 (22th of august 1962) thebigday.setdate(0); // 1962-07-31 (31th of july 1962) thebigday.setdate(98); // 19...
Date - JavaScript
0:00 gmt+0000 (bst) calculating elapsed time the following examples show how to determine the elapsed time between two javascript dates in milliseconds. due to the differing lengths of days (due to daylight saving changeover), months, and years, expressing elapsed time in units greater than hours, minutes, and seconds requires addressing a number of issues, and should be thoroughly researched before being attempted. // using date objects let start = date.now() // the event to time goes here: dosomethingforalongtime() let end = date.now() let elapsed = end - start // elapsed time in milliseconds // using built-in methods let start = new date() // the event to time goes here: dosomethingforalongtime() let end = new date() let elapsed = end.gettime() - start.gettime() // elapsed time in mi...
Error.prototype.stack - JavaScript
however, safari 6+ and opera 12- use a very similar format. browsers using the v8 javascript engine (such as chrome, opera 15+, android browser) and ie10+, on the other hand, uses a different format (see the archived msdn error.stack docs). argument values in the stack: prior to firefox 14, the function name would be followed by the argument values converted to string in parentheses immediately before the at (@) sign. while an object (or array, etc.) would appear in the converted form "[object object]", and as such could not be evaluated back into the actual objects, scalar values could be retrieved (though it may be — it is still possible in firefox 14 — easier to use arguments.callee.caller.arguments, as could the function name be retrieved by arguments.callee.caller.name). "undefined" i...
Float32Array() constructor - JavaScript
length argument, an internal array buffer is created in memory, of size length multiplied by bytes_per_element bytes, containing zeros. typedarray when called with a typedarray argument, which can be an object of any of the typed array types (such as int32array), the typedarray gets copied into a new typed array. each value in typedarray is converted to the corresponding type of the constructor before being copied into the new array. the length of the new typed array will be same as the length of the typedarray argument. object when called with an object argument, a new typed array is created as if by the typedarray.from() method. buffer, byteoffset, length when called with a buffer, and optionally a byteoffset and a length argument, a new typed array view is created that views the specifi...
Float64Array() constructor - JavaScript
length argument, an internal array buffer is created in memory, of size length multiplied by bytes_per_element bytes, containing zeros. typedarray when called with a typedarray argument, which can be an object of any of the typed array types (such as int32array), the typedarray gets copied into a new typed array. each value in typedarray is converted to the corresponding type of the constructor before being copied into the new array. the length of the new typed array will be same as the length of the typedarray argument. object when called with an object argument, a new typed array is created as if by the typedarray.from() method. buffer, byteoffset, length when called with a buffer, and optionally a byteoffset and a length argument, a new typed array view is created that views the specifi...
Function.arguments - JavaScript
tack, the value of f.arguments represents the arguments corresponding to the most recent invocation of the function. the value of the arguments property is normally null if there is no outstanding invocation of the function in progress (that is, the function has been called but has not yet returned. examples using the arguments object function f(n) { g(n - 1) } function g(n) { console.log('before: ' + g.arguments[0]) if (n > 0) { f(n) } console.log('after: ' + g.arguments[0]) } f(2) console.log('returned: ' + g.arguments) // output // before: 1 // before: 0 // after: 0 // after: 1 // returned: null specifications not part of any standard. deprecated in favor of arguments in ecmascript 3. ...
Int16Array() constructor - JavaScript
length argument, an internal array buffer is created in memory, of size length multiplied by bytes_per_element bytes, containing zeros. typedarray when called with a typedarray argument, which can be an object of any of the typed array types (such as int32array), the typedarray gets copied into a new typed array. each value in typedarray is converted to the corresponding type of the constructor before being copied into the new array. the length of the new typed array will be same as the length of the typedarray argument. object when called with an object argument, a new typed array is created as if by the typedarray.from() method. buffer, byteoffset, length when called with a buffer, and optionally a byteoffset and a length argument, a new typed array view is created that views the specifi...
Int32Array() constructor - JavaScript
length argument, an internal array buffer is created in memory, of size length multiplied by bytes_per_element bytes, containing zeros. typedarray when called with a typedarray argument, which can be an object of any of the typed array types (such as int32array), the typedarray gets copied into a new typed array. each value in typedarray is converted to the corresponding type of the constructor before being copied into the new array. the length of the new typed array will be same as the length of the typedarray argument. object when called with an object argument, a new typed array is created as if by the typedarray.from() method. buffer, byteoffset, length when called with a buffer, and optionally a byteoffset and a length argument, a new typed array view is created that views the specifi...
Int8Array() constructor - JavaScript
length argument, an internal array buffer is created in memory, of size length multiplied by bytes_per_element bytes, containing zeros. typedarray when called with a typedarray argument, which can be an object of any of the typed array types (such as int32array), the typedarray gets copied into a new typed array. each value in typedarray is converted to the corresponding type of the constructor before being copied into the new array. the length of the new typed array will be same as the length of the typedarray argument. object when called with an object argument, a new typed array is created as if by the typedarray.from() method. buffer, byteoffset, length when called with a buffer, and optionally a byteoffset and a length argument, a new typed array view is created that views the specifi...
Intl.Collator.prototype.compare() - JavaScript
one https://github.com/mdn/interactive-examples and send us a pull request. syntax collator.compare(string1, string2) parameters string1 string2 the strings to compare against each other. description the compare getter function returns a number indicating how string1 and string2 compare to each other according to the sort order of this collator object: a negative value if string1 comes before string2; a positive value if string1 comes after string2; 0 if they are considered equal. examples using compare for array sort use the compare getter function for sorting arrays. note that the function is bound to the collator from which it was obtained, so it can be passed directly to array.prototype.sort(). var a = ['offenbach', 'Österreich', 'odenwald']; var collator = new intl.collator(...
Intl.Locale.prototype.caseFirst - JavaScript
ed to determine how strings are ordered in that locale. certain locales use a character's case (uppercase or lowercase) in the collation process. this additional rule can be expressed in a locale's casefirst property. there are 3 values that the casefirst property can have, outlined in the table below. casefirst values value description upper upper case to be sorted before lower case. lower lower case to be sorted before upper case. false no special case ordering. examples setting the casefirst value via the locale string in the unicode locale string spec, the values that casefirst represents correspond to the key kf. kf is treated as a locale string "extension subtag". these subtags add additional data about the locale, and are add...
JSON.stringify() - JavaScript
storedsession = json.parse(localstorage.getitem('session')); // now restoredsession variable contains the object that was saved // in localstorage console.log(restoredsession); well-formed json.stringify() engines implementing the well-formed json.stringify specification will stringify lone surrogates, any code point from u+d800 to u+dfff, using unicode escape sequences rather than literally. ...
Map.prototype.forEach() - JavaScript
g parameter is provided to foreach, it will be passed to callback when invoked, for use as its this value. otherwise, the value undefined will be passed for use as its this value. the this value ultimately observable by callback is determined according to the usual rules for determining the this seen by a function. each value is visited once, except in the case when it was deleted and re-added before foreach has finished. callback is not invoked for values deleted before being visited. new values added before foreach has finished will be visited. foreach executes the callback function once for each element in the map object. it does not return a value. examples printing the contents of a map object the following code logs a line for each element in an map object: function logmapelements(...
Number.NEGATIVE_INFINITY - JavaScript
a static property of number, you always use it as number.negative_infinity, rather than as a property of a number object you created. examples using negative_infinity in the following example, the variable smallnumber is assigned a value that is smaller than the minimum value. when the if statement executes, smallnumber has the value -infinity, so smallnumber is set to a more manageable value before continuing. var smallnumber = (-number.max_value) * 2; if (smallnumber === number.negative_infinity) { smallnumber = returnfinite(); } specifications specification ecmascript (ecma-262)the definition of 'number.negative_infinity' in that specification. ...
Number.POSITIVE_INFINITY - JavaScript
nity is a static property of number, you always use it as number.positive_infinity, rather than as a property of a number object you created. examples using positive_infinity in the following example, the variable bignumber is assigned a value that is larger than the maximum value. when the if statement executes, bignumber has the value infinity, so bignumber is set to a more manageable value before continuing. var bignumber = number.max_value * 2; if (bignumber == number.positive_infinity) { bignumber = returnfinite(); } specifications specification ecmascript (ecma-262)the definition of 'number.positive_infinity' in that specification. ...
Object.assign() - JavaScript
ototype if the merge sources contain getters. for copying property definitions (including their enumerability) into prototypes, use object.getownpropertydescriptor() and object.defineproperty() instead. both string and symbol properties are copied. in case of an error, for example if a property is non-writable, a typeerror is raised, and the target object is changed if any properties are added before the error is raised. note: object.assign() does not throw on null or undefined sources. polyfill this polyfill doesn't support symbol properties, since es5 doesn't have symbols anyway: if (typeof object.assign !== 'function') { // must be writable: true, enumerable: false, configurable: true object.defineproperty(object, "assign", { value: function assign(target, varargs) { // .leng...
Object.prototype.constructor - JavaScript
osition() // error undefined is not a function, since the constructor is child return { offsetx: startposition.x - position.x, offsety: startposition.y - position.y } }; for this example we need either to stay parent constructor to continue to work properly or reassign static properties to child's constructor: ... child = object.assign(parentwithstatic) // notice that we assign it before we create(...) a prototype below child.prototype = object.create(parentwithstatic.prototype) ... or assign parent constructor identifier to a separate property on the child constructor function and access it via that property: ... child.parentconstructor = parentwithstatic child.prototype = object.create(parentwithstatic.prototype) ... let startposition = this.constructor.parentconstructor...
Object.is() - JavaScript
same length with the same characters in the same order both the same object (means both object have same reference) both numbers and both +0 both -0 both nan or both non-zero and both not nan and both have the same value this is not the same as being equal according to the == operator. the == operator applies various coercions to both sides (if they are not the same type) before testing for equality (resulting in such behavior as "" == false being true), but object.is doesn't coerce either value. this is also not the same as being equal according to the === operator. the === operator (and the == operator as well) treats the number values -0 and +0 as equal and treats number.nan as not equal to nan. polyfill if (!object.is) { object.is = function(x, y) { // samev...
Object.prototype.__proto__ - JavaScript
used for inheritance, see guide article inheritance and the prototype chain. the __proto__ property is a simple accessor property on object.prototype consisting of a getter and setter function. a property access for __proto__ that eventually consults object.prototype will find this property, but an access that does not consult object.prototype will not. if some other __proto__ property is found before object.prototype is consulted, that property will hide the one found on object.prototype. examples using __proto__ var circle = function () {}; var shape = {}; var circle = new circle(); // set the object prototype. // deprecated. this is for example purposes only. do not do this in real code. shape.__proto__ = circle; // get the object prototype console.log(shape.__proto__ === circle); // t...
Promise.resolve() - JavaScript
nchronously. see how then works here. ...
Promise.prototype.then() - JavaScript
esolve('foo') // 1. receive "foo", concatenate "bar" to it, and resolve that to the next then .then(function(string) { return new promise(function(resolve, reject) { settimeout(function() { string += 'bar'; resolve(string); }, 1); }); }) // 2. receive "foobar", register a callback function to work on that string // and print it to the console, but not before returning the unworked on // string to the next then .then(function(string) { settimeout(function() { string += 'baz'; console.log(string); // foobarbaz }, 1) return string; }) // 3. print helpful messages about how the code in this section will be run // before the string is actually processed by the mocked asynchronous code in the // previous then block. .t...
Set.prototype.forEach() - JavaScript
parameter is provided to foreach(), it will be passed to callback when invoked, for use as its this value. otherwise, the value undefined will be passed for use as its this value. the this value ultimately observable by callback is determined according to the usual rules for determining the this seen by a function. each value is visited once, except in the case when it was deleted and re-added before foreach() has finished. callback is not invoked for values deleted before being visited. new values added before foreach() has finished will be visited. foreach() executes the callback function once for each element in the set object; it does not return a value. examples logging the contents of a set object the following code logs a line for each element in a set object: function logseteleme...
SharedArrayBuffer.prototype.slice() - JavaScript
e-examples and send us a pull request. syntax sab.slice() sab.slice(begin) sab.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. end optional zero-based index before which to end extraction. slice extracts up to but not including end. for example, slice(1,4) extracts the second element through the fourth element (elements indexed 1, 2, and 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 th...
String.prototype.charCodeAt() - JavaScript
e a direct match of the ascii character set. examples using charcodeat() the following example returns 65, the unicode value for a. 'abc'.charcodeat(0) // returns 65 fixing charcodeat() to handle non-basic-multilingual-plane characters if their presence earlier in the string is unknown this version might be used in for loops and the like when it is unknown whether non-bmp characters exist before the specified index position. function fixedcharcodeat(str, idx) { // ex. fixedcharcodeat('\ud800\udc00', 0); // 65536 // ex. fixedcharcodeat('\ud800\udc00', 1); // false idx = idx || 0; var code = str.charcodeat(idx); var hi, low; // high surrogate (could change last hex to 0xdb7f // to treat high private surrogates // as single characters) if (0xd800 <= code && code <= 0xdbf...
String.prototype.concat() - JavaScript
.strn] strings to concatenate to str. return value a new string containing the combined text of the strings provided. description the concat() function concatenates the string arguments to the calling string and returns a new string. changes to the original string or the returned string don't affect the other. if the arguments are not of the type string, they are converted to string values before concatenating. performance it is strongly recommended that the assignment operators (+, +=) are used instead of the concat() method. examples using concat() the following example combines strings into a new string. let hello = 'hello, ' console.log(hello.concat('kevin', '. have a nice day.')) // hello, kevin. have a nice day. let greetlist = ['hello', ' ', 'venkat', '!'] "".concat(...greet...
String.prototype.slice() - JavaScript
us a pull request. syntax str.slice(beginindex[, endindex]) parameters beginindex the zero-based index at which to begin extraction. if negative, it is treated as str.length + beginindex. (for example, if beginindex is -3 it is treated as str.length - 3.) if beginindex is greater than or equal to str.length, slice() returns an empty string. endindex optional the zero-based index before which to end extraction. the character at this index will not be included. if endindex is omitted, slice() extracts to the end of the string. if negative, it is treated as str.length + endindex. (for example, if endindex is -3 it is treated as str.length - 3.) return value a new string containing the extracted section of the string. description slice() extracts the text from one string a...
String.prototype.trim() - JavaScript
eractive 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. polyfill running the following code before any other code will create trim() if it's not natively available. if (!string.prototype.trim) { string.prototype.trim = function () { return this.replace(/^[\s\ufeff\xa0]+|[\s\ufeff\xa0]+$/g, ''); }; } examples using trim() the following example displays the lowercase string 'foo': var orig = ' foo '; console.log(orig.trim()); // 'foo' // another example of .trim() removing whit...
String - JavaScript
calling string object of the first occurrence of searchvalue, or -1 if not found. string.prototype.lastindexof(searchvalue [, fromindex]) returns the index within the calling string object of the last occurrence of searchvalue, or -1 if not found. string.prototype.localecompare(comparestring [, locales [, options]]) returns a number indicating whether the reference string comparestring comes before, after, or is equivalent to the given string in sort order. string.prototype.match(regexp) used to match regular expression regexp against a string. string.prototype.matchall(regexp) returns an iterator of all regexp's matches. string.prototype.normalize([form]) returns the unicode normalization form of the calling string value. string.prototype.padend(targetlength [, padstring]) pads the...
TypedArray.prototype.filter() - JavaScript
it will be passed to callback when invoked, for use as its this value. otherwise, the value undefined will be passed for use as its this value. the this value ultimately observable by callback is determined according to the usual rules for determining the this seen by a function. filter() does not mutate the typed array on which it is called. the range of elements processed by filter() is set before the first invocation of callback. elements which are appended to the typed array after the call to filter() begins will not be visited by callback. if existing elements of the typed array are changed, or deleted, their value as passed to callback will be the value at the time filter() visits them; elements that are deleted are not visited. examples filtering out all small values the following ...
TypedArray.prototype.find() - JavaScript
back is invoked with three arguments: the value of the element, the index of the element, and the typed array object being traversed. if a thisarg parameter is provided to find, it will be used as the this for each invocation of the callback. if it is not provided, then undefined is used. find does not mutate the typed array on which it is called. the range of elements processed by find is set before the first invocation of callback. elements that are appended to the typed array after the call to find begins will not be visited by callback. if an existing, unvisited element of the typed array is changed by callback, its value passed to the visiting callback will be the value at the time that find visits that element's index; elements that are deleted are not visited. examples find a prime n...
TypedArray.prototype.findIndex() - JavaScript
with three arguments: the value of the element, the index of the element, and the typed array object being traversed. if a thisarg parameter is provided to findindex, it will be used as the this for each invocation of the callback. if it is not provided, then undefined is used. findindex does not mutate the typed array on which it is called. the range of elements processed by findindex is set before the first invocation of callback. elements that are appended to the typed array after the call to findindex begins will not be visited by callback. if an existing, unvisited element of the typed array is changed by callback, its value passed to the visiting callback will be the value at the time that findindex visits that element's index; elements that are deleted are not visited. polyfill typ...
TypedArray.prototype.forEach() - JavaScript
ing traversed if a thisarg parameter is provided to foreach(), it will be passed to callback when invoked, for use as its this value. otherwise, the value undefined will be passed for use as its this value. the this value ultimately observable by callback is determined according to the usual rules for determining the this seen by a function. the range of elements processed by foreach() is set before the first invocation of callback. elements that are appended to the typed array after the call to foreach() begins will not be visited by callback. if the values of existing elements of the typed array are changed, the value passed to callback will be the value at the time foreach() visits them; elements that are deleted before being visited are not visited. foreach() executes the callback funct...
TypedArray.prototype.map() - JavaScript
when invoked, for use as its this value. otherwise, the value undefined will be passed for use as its this value. the this value ultimately observable by mapfn is determined according to the usual rules for determining the this seen by a function. map() does not mutate the typed array on which it is called (although mapfn, if invoked, may do so). the range of elements processed by map() is set before the first invocation of mapfn. elements which are appended to the array after the call to map() begins will not be visited by mapfn. if existing elements of the 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. examples mapping a typed array to a typed array of square roots the followi...
TypedArray.prototype.slice() - JavaScript
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. end optional zero-based index before which to end extraction. slice extracts up to but not including end. for example, slice(1,4) extracts the second element through the fourth element (elements indexed 1, 2, and 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 th...
TypedArray - JavaScript
length argument, an internal array buffer is created in memory, of size length multiplied by bytes_per_element bytes, containing zeros. typedarray when called with a typedarray argument, which can be an object of any of the typed array types (such as int32array), the typedarray gets copied into a new typed array. each value in typedarray is converted to the corresponding type of the constructor before being copied into the new array. the length of the new typed array will be same as the length of the typedarray argument. object when called with an object argument, a new typed array is created as if by the typedarray.from() method. buffer, byteoffset, length when called with a buffer, and optionally a byteoffset and a length argument, a new typed array view is created that views the specifi...
Uint16Array() constructor - JavaScript
length argument, an internal array buffer is created in memory, of size length multiplied by bytes_per_element bytes, containing zeros. typedarray when called with a typedarray argument, which can be an object of any of the typed array types (such as int32array), the typedarray gets copied into a new typed array. each value in typedarray is converted to the corresponding type of the constructor before being copied into the new array. the length of the new typed array will be same as the length of the typedarray argument. object when called with an object argument, a new typed array is created as if by the typedarray.from() method. buffer, byteoffset, length when called with a buffer, and optionally a byteoffset and a length argument, a new typed array view is created that views the specifi...
Uint32Array() constructor - JavaScript
length argument, an internal array buffer is created in memory, of size length multiplied by bytes_per_element bytes, containing zeros. typedarray when called with a typedarray argument, which can be an object of any of the typed array types (such as int32array), the typedarray gets copied into a new typed array. each value in typedarray is converted to the corresponding type of the constructor before being copied into the new array. the length of the new typed array will be same as the length of the typedarray argument. object when called with an object argument, a new typed array is created as if by the typedarray.from() method. buffer, byteoffset, length when called with a buffer, and optionally a byteoffset and a length argument, a new typed array view is created that views the specifi...
Uint8Array() constructor - JavaScript
length argument, an internal array buffer is created in memory, of size length multiplied by bytes_per_element bytes, containing zeros. typedarray when called with a typedarray argument, which can be an object of any of the typed array types (such as int32array), the typedarray gets copied into a new typed array. each value in typedarray is converted to the corresponding type of the constructor before being copied into the new array. the length of the new typed array will be same as the length of the typedarray argument. object when called with an object argument, a new typed array is created as if by the typedarray.from() method. buffer, byteoffset, length when called with a buffer, and optionally a byteoffset and a length argument, a new typed array view is created that views the specifi...
Uint8ClampedArray() constructor - JavaScript
length argument, an internal array buffer is created in memory, of size length multiplied by bytes_per_element bytes, containing zeros. typedarray when called with a typedarray argument, which can be an object of any of the typed array types (such as int32array), the typedarray gets copied into a new typed array. each value in typedarray is converted to the corresponding type of the constructor before being copied into the new array. the length of the new typed array will be same as the length of the typedarray argument. object when called with an object argument, a new typed array is created as if by the typedarray.from() method. buffer, byteoffset, length when called with a buffer, and optionally a byteoffset and a length argument, a new typed array view is created that views the specifi...
WeakRef - JavaScript
orks.) if multiple weakrefs have the same target, they're consistent with one another. the result of calling deref on one of them will match the result of calling deref on another of them (in the same job), you won't get the target object from one of them but undefined from another. if the target of a weakref is also in a finalizationregistry, the weakref's target is cleared at the same time or before any cleanup callback associated with the registry is called; if your cleanup callback calls deref on a weakref for the object, it will receive undefined. you cannot change the target of a weakref, it will always only ever be the original target object or undefined when that target has been reclaimed. a weakref might never return undefined from deref, even if nothing strongly holds the target, b...
WebAssembly.compile() - JavaScript
syntax promise<webassembly.module> webassembly.compile(buffersource); parameters buffersource a typed array or arraybuffer containing the binary code of the .wasm module you want to compile. return value a promise that resolves to a webassembly.module object representing the compiled module. ...
WebAssembly.compileStreaming() - JavaScript
syntax promise<webassembly.module> webassembly.compilestreaming(source); parameters source a response object or a promise that will fulfill with one, representing the underlying source of a .wasm module you want to stream and compile. ...
Bitwise AND (&) - JavaScript
ples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax a & b description the operands are converted to 32-bit integers and expressed by a series of bits (zeroes and ones). numbers with more than 32 bits get their most significant bits discarded. for example, the following integer with more than 32 bits will be converted to a 32 bit integer: before: 11100110111110100000000000000110000000000001 after: 10100000000000000110000000000001 each bit in the first operand is paired with the corresponding bit in the second operand: first bit to first bit, second bit to second bit, and so on. the operator is applied to each pair of bits, and the result is constructed bitwise. the truth table for the and operation is: a b ...
Bitwise NOT (~) - JavaScript
xamples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax ~a description the operands are converted to 32-bit integers and expressed by a series of bits (zeroes and ones). numbers with more than 32 bits get their most significant bits discarded. for example, the following integer with more than 32 bits will be converted to a 32 bit integer: before: 11100110111110100000000000000110000000000001 after: 10100000000000000110000000000001 each bit in the first operand is paired with the corresponding bit in the second operand: first bit to first bit, second bit to second bit, and so on. the operator is applied to each pair of bits, and the result is constructed bitwise. the truth table for the not operation is: a not ...
Bitwise OR (|) - JavaScript
ples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax a | b description the operands are converted to 32-bit integers and expressed by a series of bits (zeroes and ones). numbers with more than 32 bits get their most significant bits discarded. for example, the following integer with more than 32 bits will be converted to a 32 bit integer: before: 11100110111110100000000000000110000000000001 after: 10100000000000000110000000000001 each bit in the first operand is paired with the corresponding bit in the second operand: first bit to first bit, second bit to second bit, and so on. the operator is applied to each pair of bits, and the result is constructed bitwise. the truth table for the or operation is: a b ...
Bitwise XOR (^) - JavaScript
ples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax a ^ b description the operands are converted to 32-bit integers and expressed by a series of bits (zeroes and ones). numbers with more than 32 bits get their most significant bits discarded. for example, the following integer with more than 32 bits will be converted to a 32 bit integer: before: 11100110111110100000000000000110000000000001 after: 10100000000000000110000000000001 each bit in the first operand is paired with the corresponding bit in the second operand: first bit to first bit, second bit to second bit, and so on. the operator is applied to each pair of bits, and the result is constructed bitwise. the truth table for the xor operation is: a b ...
Comma operator (,) - JavaScript
ill evaluates and its result returned to console (i.e., 4). this is due to operator precedence and associativity. var a, b, c; a = b = 3, c = 4; // returns 4 in console console.log(a); // 3 (left-most) var x, y, z; x = (y = 5, z = 6); // returns 6 in console console.log(x); // 6 (right-most) processing and then returning another example that one could make with comma operator is processing before returning. as stated, only the last element will be returned but all others are going to be evaluated as well. so, one could do: function myfunc() { var x = 0; return (x += 1, x); // the same as return ++x; } specifications specification ecmascript (ecma-262)the definition of 'comma operator' in that specification. ...
Decrement (--) - JavaScript
lue. the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax operator: x-- or --x description if used postfix, with operator after operand (for example, x--), the decrement operator decrements and returns the value before decrementing. if used prefix, with operator before operand (for example, --x), the decrement operator decrements and returns the value after decrementing. examples postfix decrement let x = 3; y = x--; // y = 3 // x = 2 prefix decrement let a = 2; b = --a; // a = 1 // b = 1 specifications specification ecmascript (ecma-262)the definition of 'decrement operator' in th...
Equality (==) - JavaScript
ription the equality operators (== and !=) use the abstract equality comparison algorithm to compare two operands. this can be roughly summarised as follows: if the operands are both objects, return true only if both operands reference the same object. if one operand is null and the other is undefined, return true. if the operands are of different types, try to convert them to the same type before comparing: when comparing a number to a string, try to convert the string to a numeric value. if one of the operands is boolean, convert the 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 operan...
Exponentiation (**) - JavaScript
iation operator is defined to have a higher precedence than unary operators, such as unary + and unary -, but there are a few exceptions. for example, in bash, the ** operator is defined to have a lower precedence than unary operators. in javascript, it is impossible to write an ambiguous exponentiation expression. that is, you cannot put a unary operator (+/-/~/!/delete/void/typeof) immediately before the base number; doing so will cause a syntaxerror. -2 ** 2; // 4 in bash, -4 in other languages. // this is invalid in javascript, as the operation is ambiguous. -(2 ** 2); // -4 in javascript and the author's intention is unambiguous. note that some programming languages use the caret symbol ^ for exponentiation, but javascript uses that symbol for the bitwise logical xor operator. exampl...
Increment (++) - JavaScript
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 operator: x++ or ++x description if used postfix, with operator after operand (for example, x++), the increment operator increments and returns the value before incrementing. if used prefix, with operator before operand (for example, ++x), the increment operator increments and returns the value after incrementing. examples postfix increment let x = 3; y = x++; // y = 3 // x = 4 prefix increment let a = 2; b = ++a; // a = 3 // b = 3 specifications specification ecmascript (ecma-262)the definition of 'increment operator' in th...
Logical AND (&&) - JavaScript
st operand. see example: function a(){ console.log('called a'); return false; } function b(){ console.log('called b'); return true; } console.log( a() && b() ); // logs "called a" due to the function call, // then logs false (which is the resulting value of the operator) operator precedence the following expressions might seem equivalent, but they are not, because the && operator is executed before the || operator (see operator precedence). true || false && false // returns true, because && is executed first (true || false) && false // returns false, because operator precedence cannot apply examples using and the following code shows examples of the && (logical and) operator. a1 = true && true // t && t returns true a2 = true && false // t && f returns false a3 = f...
Logical OR (||) - JavaScript
rst operand. see example: function a(){ console.log('called a'); return false; } function b(){ console.log('called b'); return true; } console.log( b() || a() ); // logs "called b" due to the function call, // then logs true (which is the resulting value of the operator) operator precedence the following expressions might seem equivalent, but they are not, because the && operator is executed before the || operator (see operator precedence). true || false && false // returns true, because && is executed first (true || false) && false // returns false, because operator precedence cannot apply examples using or the following code shows examples of the || (logical or) operator. o1 = true || true // t || t returns true o2 = false || true // f || t returns true o3 = true...
Operator precedence - JavaScript
luating the middle side evaluating the right side 64 looking at the code snippets above, 6 / 3 / 2 is the same as (6 / 3) / 2 because division is left-associative. exponentiation, on the other hand, is right-associative, so 2 ** 3 ** 2 is the same as 2 ** (3 ** 2). thus, doing (2 ** 3) ** 2 changes the order and results in the 64 seen in the table above. remember that precedence comes before associativity. so, mixing division and exponentiation, the exponentiation comes before the division. for example, 2 ** 3 / 3 ** 2 results in 0.8888888888888888 because it is the same as (2 ** 3) / (3 ** 2). note on grouping and short-circuiting in the table below, grouping is listed as having the highest precedence. however, that does not always mean the expression within the grouping symbols (...
Strict equality (===) - JavaScript
ues: numbers must have the same numeric values. +0 and -0 are considered to be the same value. strings must have the same characters in the same order. booleans must be both true or both false. the most notable difference between this operator and the equality (==) operator is that if the operands are of different types, the == operator attempts to convert them to the same type before comparing. examples comparing operands of the same type console.log("hello" === "hello"); // true console.log("hello" === "hola"); // false console.log(3 === 3); // true console.log(3 === 4); // false console.log(true === true); // true console.log(true === false); // false console.log(null === null); // true comparing operands of dif...
await - JavaScript
tion after fulfillment. when resumed, the value of the await expression is that of the fulfilled promise. if the promise is rejected, the await expression throws the rejected value. if the value of the expression following the await operator is not a promise, it's converted to a resolved promise. an await can split execution flow, allowing the caller of the await's function to resume execution before the deferred continuation of the await's function. after the await defers the continuation of its function, if this is the first await executed by the function, immediate execution also continues by returning to the function's caller a pending promise for the completion of the await's function and resuming execution of that caller. examples awaiting a promise to be fulfilled if a promise is pa...
Function expression - JavaScript
an be omitted in function expressions to create anonymous functions. a function expression can be used as an iife (immediately invoked function expression) which runs as soon as it is defined. see also the chapter about functions for more information. function expression hoisting function expressions in javascript are not hoisted, unlike function declarations. you can't use function expressions before you create them: console.log(nothoisted) // undefined // even though the variable name is hoisted, the definition isn't. so it's undefined. nothoisted(); // typeerror: nothoisted is not a function var nothoisted = function() { console.log('bar'); }; named function expression if you want to refer to the current function inside the function body, you need to create a named function express...
instanceof - JavaScript
specifications specification ecmascript (ecma-262)the definition of 'relational operators' in that specification. ...
this - JavaScript
methods are not properties of this. they are properties of the class itself. derived classes unlike base class constructors, derived constructors have no initial this binding. calling super() creates a this binding within the constructor and essentially has the effect of evaluating the following line of code, where base is the inherited class: this = new base(); warning: referring to this before calling super() will throw an error. derived classes must not return before calling super(), unless they return an object or have no constructor at all. class base {} class good extends base {} class alsogood extends base { constructor() { return {a: 5}; } } class bad extends base { constructor() {} } new good(); new alsogood(); new bad(); // referenceerror examples this in functi...
block - JavaScript
t have block scope. 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 introduce a scope. for example: var x = 1; { var x = 2; } console.log(x); // logs 2 this logs 2 because the var x statement within the block is in the same scope as the var x statement before the block. in non-strict code, function declarations inside blocks behave strangely. do not use them. block scoping rules with let, const or function declaration in strict mode by contrast, identifiers declared with let and const do have block scope: let x = 1; { let x = 2; } console.log(x); // logs 1 the x = 2 is limited in scope to the block in which it was defined. the same is true of ...
for await...of - JavaScript
length. responsesize += chunk.length; } console.log(`response size: ${responsesize} bytes`); // expected output: "response size: 1071472" return responsesize; } getresponsesize('https://jsonplaceholder.typicode.com/photos'); iterating over sync iterables and generators for await...of loop also consumes sync iterables and generators. in that case it internally awaits emitted values before assign them to the loop control variable. function* generator() { yield 0; yield 1; yield promise.resolve(2); yield promise.resolve(3); yield 4; } (async function() { for await (let num of generator()) { console.log(num); } })(); // 0 // 1 // 2 // 3 // 4 // compare with for-of loop: for (let numorpromise of generator()) { console.log(numorpromise); } // 0 // 1 // promise {...
function declaration - JavaScript
is hoisted. typeof foo is undefined // // in firefox: // 'foo' name is hoisted. typeof foo is undefined // // in edge: // 'foo' name is not hoisted. typeof foo is undefined // // in safari: // 'foo' name is hoisted. typeof foo is function function declaration hoisting function declarations in javascript are hoisted to the top of the enclosing function or global scope. ...
let - JavaScript
new block scoped lexical environment, which will not produce the redeclaration errors shown above. let x = 1; switch(x) { case 0: { let foo; break; } case 1: { let foo; break; } } temporal dead zone unlike variables declared with var, which will start with the value undefined, let variables are not initialized until their definition is evaluated. accessing the variable before the initialization results in a referenceerror. the variable is in a "temporal dead zone" from the start of the block until the initialization is processed. function do_something() { console.log(bar); // undefined console.log(foo); // referenceerror var bar = 1; let foo = 2; } the temporal dead zone and typeof unlike with simply undeclared variables and variables that hold a value of u...
switch - JavaScript
methods for multi-criteria case source for this technique is here: switch statement multiple cases in javascript (stack overflow) multi-case : single operation this method takes advantage of the fact that if there is no break below a case clause it will continue to execute the next case clause regardless if the case meets the criteria. (see the section what happens if i forg...
try...catch - JavaScript
e exception value. you can use this identifier to get information about the exception that was thrown. this identifier is only available in the catch-block's scope. function isvalidjson(text) { try { json.parse(text); return true; } catch { return false; } } the finally-block the finally-block contains statements to execute after the try-block and catch-block(s) execute, but before the statements following the try...catch...finally-block. note that the finally-block executes regardless of whether an exception is thrown. also, if an exception is thrown, the statements in the finally-block execute even if no catch-block handles the exception. the following example shows one use case for the finally-block. the code opens a file and then executes statements that use the file; ...
Statements and declarations - JavaScript
ts to be executed for the value of each distinct property. for await...of iterates over async iterable objects, array-like objects, iterators and generators, invoking a custom iteration hook with statements to be executed for the value of each distinct property. while creates a loop that executes a specified statement as long as the test condition evaluates to true. the condition is evaluated before executing the statement. others debugger invokes any available debugging functionality. if no debugging functionality is available, this statement has no effect. export used to export functions to make them available for imports in external modules, and other scripts. import used to import functions exported from an external module, another script. import.meta an object exposing conte...
Template literals (Template strings) - JavaScript
he expressions in the placeholders and the text between the backticks (` `) get passed to a function. the default function just concatenates the parts into a single string. if there is an expression preceding the template literal (tag here), this is called a tagged template. in that 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. using normal strings, you would have to use the following syntax in order to get multi-line strings: console.log('string text line 1\n' + 'string text line 2'); // "string ...
JavaScript typed arrays - JavaScript
re with a fixed length of 16-bytes: let buffer = new arraybuffer(16); at this point, we have a chunk of memory whose bytes are all pre-initialized to 0. there's not a lot we can do with it, though. we can confirm that it is indeed 16 bytes long, and that's about it: if (buffer.bytelength === 16) { console.log("yes, it's 16 bytes."); } else { console.log("oh no, it's the wrong size!"); } before we can really work with this buffer, we need to create a view. let's create a view that treats the data in the buffer as an array of 32-bit signed integers: let int32view = new int32array(buffer); now we can access the fields in the array just like a normal array: for (let i = 0; i < int32view.length; i++) { int32view[i] = i * 2; } this fills out the 4 entries in the array (4 entries at 4...
categories - Web app manifests
of categories that the application supposedly belongs to. there is no standard list of possible values, but the w3c maintains a list of known categories. note: categories are used only as hints for catalogs or stores listing web applications. like search engines and meta keywords, catalogs and stores are free to ignore them. note: categories values are lower-cased by the stores and catalogs before processing, so "news" and "news" are treated as the same value. developers are encouraged to use lower case in the first place. example "categories": ["books", "education", "medical"] specification specification status comment feedback web app manifestthe definition of 'categories' in that specification. working draft initial defin...
MathML attribute reference - MathML
implemented linebreakstyle <mo>, <mspace> unimplemented lineleading <mo>, <mspace> linethickness <mfrac> the thickness of the horizontal fraction line. unimplemented location <mscarries> unimplemented longdivstyle <mlongdiv> controls the style of the long division layout. lspace <mo>, <mpadded> the amount of space before the operator (see length for values and units). lquote <ms> the opening quote character (depends on dir) to enclose the content. the default value is "&quot;". mathbackground all the background color. you can use #rgb, #rrggbb and html color names. mathcolor all the text color. you can use #rgb, #rrggbb and html color names. mathsize <mi>, ...
<mo> - MathML
Web › MathML › Element › mo
uded in a <mrow> element.) postfix, closing fences. (it is the default value if the operator is the last argument in a <mrow> element with more than one argument.) href used to set a hyperlink to a specified uri. largeop specifies whether the operator should be drawn larger than normal when displaystyle="true" is set. allowed values are either true or false. lspace the amount of space before the operator (see length for values and units). the constant thickmathspace (5/18em) is the default value. mathbackground the background color. you can use #rgb, #rrggbb and html color names. mathcolor the text color. you can use #rgb, #rrggbb and html color names. mathsize the size of the content. see length for possible values. deprecated values are: small, normal and big. these will be ...
<mstyle> - MathML
Web › MathML › Element › mstyle
oolean 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. 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 values before, after and duplicate are allowed. scriptlevel controls mostly the font-size. the higher the scriptlevel, the smaller the font size. this attribute accepts a non-negative integer, as well as a "+" or a "-" sign, which increments or decrements the current value. in addition, the scriptlevel attribute can never reduce the font size below scriptminsize in order to avoid unreadable small font sizes ...
Web audio codec guide - Web media technologies
atency during music playback, you should strongly consider opus, which has the lowest range of latencies of the general-purpose codecs (5 ms to 66.5 ms, compared to at least 100 ms for the others). note: compatibility information described here is generally correct as of the time this article was written; however, there may be caveats and exceptions. be sure to refer to the compatibility tables before committing to a given media format. based on this, aac is likely your best choice if you can only support one audio format. of course, if you can provide multiple formats (for example, by using the <source> element within your <audio> and <video> elements), you can avoid many or all of those exceptions. example: music for download music being downloaded by the user can be compressed to a larg...
The "codecs" parameter in common media types - Web media technologies
onstraints byte constrained baseline profile (cbp) cbp is primarily a solution for scenarios in which resources are constrained, or resource use needs to be controlled to minimize the odds of the media performing poorly. 42 40 baseline profile (bp) similar to cbp but with more data loss protections and recovery capabilities. this is not as widely used as it was before cbp was introduced. all cbp streams are considered to also be bp streams. 42 00 extended profile (xp) designed for streaming video over the network, with high compression capability and further improvements to data robustness and stream switching. 58 00 main profile (mp) the profile used for standard-definition digital television being broadcast in mpeg-4 for...
Using images in HTML - Web media technologies
Web › Media › images
pabilities, and compatibility factors. additionally, this article provides guidance for selecting the best image file type for a given situation. mapping the width and height attributes of media container elements to their aspect-ratio this changes how browsers load images so their aspect ratios are calculated by the browser early on and can later be used to correct the display size of an image before it's loaded. other topics related topics that may be of interest. learn html: responsive images in this article, we'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. ...
OpenSearch description format
hould be the url of the opensearch document to automatically update to. for example: <url type="application/opensearchdescription+xml" rel="self" template="https://example.com/mysearchdescription.xml" /> note: at this time, addons.mozilla.org (amo) doesn't support automatic updating of opensearch plugins. if you want to put your search plugin on amo, remove the auto-updating feature before submitting it. troubleshooting tips if there is a mistake in your search plugin xml, you could run into errors when adding a discovered plugin. if the error message isn't be helpful, the following tips could help you find the problem. your server should serve opensearch plugins using content-type: application/opensearchdescription+xml. be sure that your search plugin xml is well formed. you...
Performance Monitoring: RUM vs synthetic monitoring - Web Performance
ng tail. synthetic monitoring can be an important component of regression testing and production site monitoring. test the site at every stage of development and regularly in production. changes from baseline performance as part of continuous integration should fail a push. if an issue arises in production, synthetic monitoring can provide insight, helping identify, isolate, and resolve problems before they negatively user experience. real user monitoring real user monitoring or rum measures the performance of a page from real users' machines. generally, a third party script injects a script on each page to measure and report back on page load data for every request made. this technique monitors an application’s actual user interactions. in real user monitoring, the browsers of real users r...
Using dns-prefetch - Web Performance
this process is known as dns resolution. while dns caching can help to reduce this latency, dns resolution can add significant latency to requests. for websites that open connections to many third parties, this latency can significantly reduce loading performance. dns-prefetch helps developers mask dns resolution latency. ...
Introduction to progressive web apps - Progressive web apps (PWAs)
s to ensure that they're installing the right app, because its url will match your site's domain. this is very different from apps in app stores, which may have a number of similarly-named apps, some of which may even be based on your own site, which only adds to the confusion. web apps eliminate that confusion and ensure that users get the best possible experience. browser support as mentioned before, pwas don't depend on a single api, but rather using various technologies to achieve the goal of delivering the best web experience possible. the key ingredient required for pwas is service worker support. thankfully service workers are now supported on all major browsers on desktop and mobile. other features such as web app manifest, push notifications, and add to home screen functionality h...
How to make PWAs re-engageable using Notifications and Push - Progressive web apps (PWAs)
t a very early stage — some working examples use the google cloud messaging platform, but are being rewritten to support vapid (voluntary application identification), which offers an extra layer of security for your app. you can examine the service workers cookbook examples, try to set up a push messaging server using firebase, or build your own server (using node.js for example). as mentioned before, to be able to receive push messages, you have to have a service worker, the basics of which are already explained in the making pwas work offline with service workers article. inside the service worker, a push service subscription mechanism is created. registration.pushmanager.getsubscription() .then( /* ... */ ); once the user is subscribed, they can receive push notifications from the server...
Graphic design for responsive sites - Progressive web apps (PWAs)
power and bandwidth available, so you want to reduce the processing and downloads. in addition, mobile devices have smaller screen sizes, so it makes sense to reduce visual clutter on a mobile layout. css media queries allow us to serve different css rules dependant on viewport dimensions, and you should consider using mobile first media queries where possible. this means that the default layout before any media queries are encountered in the css is the small screen/mobile layout, not the wide screen/desktop layout. so when the page is loaded on a mobile device, the mobile will only download the mobile assets, and not the desktop resource assets. making html <img>s responsive is not as easy, as there is currently no native mechanism to serve different html images depending on context. there ar...
SVG Conditional Processing Attributes - SVG: Scalable Vector Graphics
can be specified on some svg elements to control whether or not the element on which it appears should be rendered. externalresourcesrequired requiredextensions requiredfeatures systemlanguage attributes externalresourcesrequired deprecated since svg 2 if set to true, it indicates that the browser must wait for all the external resources necessary to render that element to be loaded before processing the associated element. value: false|true; animatable: no requiredextensions list all the browser specific capabilities that must be supported by the borwser to be allowed to render the associated element. value: a list of space-separated uri; animatable: no requiredfeatures deprecated since svg 2 list all the features, as defined is the svg 1.1 specification, that must be suppor...
SVG Presentation Attributes - SVG: Scalable Vector Graphics
troke 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 object is aligned along the font baseline with respect to its parent. value: auto|baseline|before-edge|text-before-edge|middle|central|after-edge|text-after-edge|ideographic|alphabetic|hanging|mathematical|inherit; animatable: yes baseline-shift it allows repositioning of the dominant-baseline relative to the dominant-baseline of the parent text content element. value: auto|baseline|super|sub|<percentage>|<length>|inherit; animatable: yes clip deprecated it defines what portion of an ele...
begin - SVG: Scalable Vector Graphics
Web › SVG › Attribute › begin
nt is fired. a valid event-value consists of an element id followed by a dot and one of the supported events for that element. all valid events (not necessarily supported by all elements) are defined by the dom and html specifications. those are: focus, blur, focusin, focusout, activate, auxclick, click, dblclick, mousedown, mouseenter, mouseleave, mousemove, mouseout, mouseover, mouseup, wheel, beforeinput, input, keydown, keyup, compositionstart, compositionupdate, compositionend, load, unload, 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 start time is defined relative to the time that the repeat event is rai...
class - SVG: Scalable Vector Graphics
Web › SVG › Attribute › class
gories none value <list-of-class-names> animatable yes normative document svg 1.1 (2nd edition): the class attribute list-of-ts <list-of-ts> (where t is some type.) a list consists of a separated sequence of values. unless explicitly described differently, lists within svg's xml attributes can be either comma-separated (with optional white space before or after the comma), or white space-separated. white space in lists is defined as one or more of the following consecutive characters: "space" (u+0020), "tab" (u+0009), "line feed" (u+000a), "carriage return" (u+000d), and "form-feed" (u+000c). the following is a template for an ebnf grammar describing the <list-of-ts> syntax: list-of-ts ::= t | t, list-of-ts within the svg...
dominant-baseline - SVG: Scalable Vector Graphics
er-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 of which font baseline-table to use from the baseline-tables in the font is browser dependent. the baseline-table font-size is changed to the value of the font-size attribute on this element. text-before-edge the baseline-identifier for the dominant-baseline is set to be text-before-edge. the derived baseline-table is constructed from the defined baselines in a baseline-table in the font. the choice of which baseline-table to use from the baseline-tables in the font is browser dependent. the baseline-table font-size is changed to the value of the font-size attribute on this element. text-top t...
end - SVG: Scalable Vector Graphics
Web › SVG › Attribute › end
t is fired. a valid event-value consists of an element id followed by a dot and one of the supported events for that element. all valid events (not necessarily supported by all elements) are defined by the dom and html specifications. those are: focus, blur, focusin, focusout, activate, auxclick, click, dblclick, mousedown, mouseenter, mouseleave, mousemove, mouseout, mouseover, mouseup, wheel, beforeinput, input, keydown, keyup, compositionstart, compositionupdate, compositionend, load, unload, 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 rais...
href - SVG: Scalable Vector Graphics
Web › SVG › Attribute › href
the href attribute defines a link to a resource as a reference url. the exact meaning of that link depends on the context of each element using it. note: specifications before svg 2 defined an xlink:href attribute, which is now rendered obsolete by the href attribute. fifteen elements are using this attribute: <a>, <animate>, <animatemotion>, <animatetransform>, <discard>, <feimage>, <image>, <lineargradient>, <mpath>, <pattern>, <radialgradient>, <script>, <set>, <textpath>, and <use> html, body, svg { height: 100%; } <svg viewbox="0 0 160 40" xmlns="http://www.w3.org/2000/svg"> <a href="https://developer.mozilla.org/"><text x="10" y="25">mdn web docs</text></a> </svg> in svg a for <a>, href defines the location of the referenced object, expressed as a url reference. ...
text-anchor - SVG: Scalable Vector Graphics
xt on a path, conceptually the text string is first laid out in a straight line. the midpoint between the start of the text string and the end of the text string is determined. then, the text string is mapped onto the path with this midpoint placed at the current text position.) end the rendered characters are shifted such that the end of the resulting rendered text (final current text position before applying the text-anchor property) is at the initial current text position. for an element with a direction property value of ltr (typical for most european languages), the right side of the text is rendered at the initial text position. for an element with a direction property value of rtl (typical for arabic and hebrew), the left side of the text is rendered at the initial text position. for an...
vector-effect - SVG: Scalable Vector Graphics
filters, masks and clips. note: as a presentation attribute, vector-effect can be used as a css property. ...
<feDiffuseLighting> - SVG: Scalable Vector Graphics
e resulting image, which is an rgba opaque image, depends on the light color, light position and surface geometry of the input bump map. the light map produced by this filter primitive can be combined with a texture image using the multiply term of the arithmetic operator of the <fecomposite> filter primitive. multiple light sources can be simulated by adding several of these light maps together before applying it to the texture image. usage context categoriesfilter primitive elementpermitted contentany number of descriptive elements and exactly one light source element, in any order. attributes global attributes core attributes presentation attributes filter primitive attributes class style specific attributes in surfacescale diffuseconstant kernelunitlength dom interface ...
<feSpecularLighting> - SVG: Scalable Vector Graphics
ation is added. the filter primitive assumes that the viewer is at infinity in the z direction. this filter primitive produces an image which contains the specular reflection part of the lighting calculation. such a map is intended to be combined with a texture using the add term of the arithmetic <fecomposite> method. multiple light sources can be simulated by adding several of these light maps before applying it to the texture image. usage context categoriesfilter primitive elementpermitted contentexactly one light source element first and any number of descriptive elements in any order. attributes global attributes core attributes presentation attributes filter primitive attributes class style specific attributes in surfacescale specularconstant specularexponent kerneluni...
SVG documentation index - SVG: Scalable Vector Graphics
Web › SVG › Index
here itʼs used, either it defines a sequence of values used over the course of an animation, or itʼs a list of numbers for a color matrix, which is interpreted differently depending on the type of color change to be performed. 239 vector-effect svg, svg attribute the vector-effect property specifies the vector effect to use when drawing an object. vector effects are applied before any of the other compositing operations, i.e. filters, masks and clips. 240 version deprecated, svg, svg attribute the version attribute is used to indicate what specification a svg document conforms to. it is only allowed on the root <svg> element. it is purely advisory and has no influence on rendering or processing. 241 vert-adv-y deprecated, svg, svg attrib...
SVG 2 support in Mozilla - SVG: Scalable Vector Graphics
on svg 1.1. those changes are listed below including their support status within mozilla applications. ...
SVG animation with SMIL - SVG: Scalable Vector Graphics
<svg width="300" height="100"> <title>svg smil animate with path</title> <rect x="0" y="0" width="300" height="100" stroke="black" stroke-width="1" /> <rect x="0" y="0" width="20" height="20" fill="blue" stroke="black" stroke-width="1"> <animatemotion path="m 250,80 h 50 q 30,80 30,50 q 30,20 50,20 h 250 q 280,20,280,50...
Gradients in SVG - SVG: Scalable Vector Graphics
like linear gradients, the <radialgradient> node can take several attributes to describe its position and orientation. however, unlike linear gradients, it's a bit more complex. the radial gradient is again defined by two points, which determine where its edges are. the first of these define...
Tools for SVG - SVG: Scalable Vector Graphics
nt tools for a graphics format is a decent drawing program. inkscape offers state-of-the-art vector drawing, and it's open source. moreover, it uses svg as its native file format. to store inkscape specific data, it extends the svg file with elements and attributes in a custom namespace, but you can also choose to export as plain svg. adobe illustrator url: www.adobe.com/products/illustrator/ before adobe acquired macromedia, it was the most prominent promoter of svg. from this time stems the good support of svg in illustrator. however, the resulting svg often shows some quirks, that make it necessary to post-process it for general applicability. apache batik url: xmlgraphics.apache.org/batik/ batik is a set of open source tools under the roof of the apache software foundation. the toolki...
Subdomain takeovers - Web security
power at the breaker or fuse box (dns) to prevent the outlet from being used by someone else. how do they happen? if the process of provisioning or deprovisioning (removing) a virtual host is not handled properly, there can be an opportunity for an attacker to take over a subdomain. during provisioning an attacker sets up a virtual host for a subdomain name you bought on the hosting provider, before you get to do it. suppose you control the domain example.com. you want to add a blog at blog.example.com, and you decide to use a hosting provider who maintains a blogging platform. (for "blog", you can substitute "e-commerce platform", "customer service platform", or any other "cloud-based" virtual hosting scenario.) the process you go through might look like this: you register the name "blo...
Web security
me>, <object>, <embed>, or <applet>. user information security insecure passwords serving login forms over http is especially dangerous because of the wide variety of attacks that can be used against them to extract a user’s password. network eavesdroppers could steal a user's password by sniffing the network, or by modifying the served page in transit. privacy and the :visited selector before about 2010, the css :visited selector allowed websites to uncover a user's browsing history and figure out what sites the user had visited. to mitigate this problem, browsers have limited the amount of information that can be obtained from visited links. security-related glossary terms block cipher mode of operation certificate authority challenge-response authentication ...
preceding-sibling - XPath
...
Axes - XPath
Web › XPath › Axes
ase, the context node must be an element node. parent indicates the single node that is the parent of the context node. it can be abbreviated as two periods (..). preceding indicates all the nodes that precede the context node in the document except any ancestor, attribute and namespace nodes. preceding-sibling indicates all the nodes that have the same parent as the context node and appear before the context node in the source document. self indicates the context node itself. it can be abbreviated as a single period (.). ...
number - XPath
the number function converts an object to a number and returns the number. syntax number( [object] ) arguments object(optional) the object to be converted to a number. if this argument is omitted, the current context node will be used. returns the resulting number after converting the object. notes strings are converted to a number by stripping the leading whitespace in the string before the number and ignoring whitespace after the number. if the string does not match this pattern, then the string is converted to nan. boolean true is converted to 1. false is converted to 0. a node-set is first converted to a string as if by a call to the string() function and then converted in the same way as a string argument. an object of a type other than the four basic types is converted t...
string - XPath
e in the set is returned. a number is converted as follows: nan is converted to the string nan. positive zero is converted to the string 0. negative zero is converted to the string 0. positive infinity is converted to the string infinity. negative infinity is converted to the string -infinity. decimal numbers between -1 and 1 are converted to a string with a single leading 0 before the decimal point. boolean true is converted to the string true. boolean false is converted to the string false. defined xpath 1.0 4.2 gecko support supported. ...
Functions - XPath
ecific document() xslt-specific element-available() false() floor() format-number() xslt-specific function-available() generate-id() xslt-specific id() (partially supported) key() xslt-specific lang() last() local-name() name() namespace-uri() normalize-space() not() number() position() round() starts-with() string() string-length() substring() substring-after() substring-before() sum() system-property() xslt-specific translate() true() unparsed-entity-url() xslt-specific (not supported) ...
<xsl:attribute> - XSLT: Extensible Stylesheet Language Transformations
but it may be after or inside elements that won't be part of the output (like <xsl:choose> or <xsl:apply-templates> etc.). ...
<xsl:for-each> - XSLT: Extensible Stylesheet Language Transformations
Web › XSLT › Element › for-each
xslt/xpath reference: xslt elements, exslt functions, xpath functions, xpath axes the <xsl:for-each> element selects a set of nodes and processes each of them in the same way. it is often used to iterate through a set of nodes or to change the current node. if one or more <xsl:sort> elements appear as the children of this element, sorting occurs before processing. otherwise, nodes are processed in document order. syntax <xsl:for-each select=expression> <xsl:sort> [optional] template </xsl:for-each> required attributes select uses an xpath expression to select nodes to be processed. optional attributes none. type instruction, appears within a template. defined xslt, section 8. gecko support supported. ...
<xsl:import> - XSLT: Extensible Stylesheet Language Transformations
Web › XSLT › Element › import
ave a lower import precedence than that of the importing stylesheet. this is in contrast to <xsl:include> where the contents of the included stylesheet have exactly the same precedence as the contents of the including stylesheet. syntax <xsl:import href=uri /> required attributes href specifies the uri of the stylesheet to import. optional attributes none. type top-level, must appear before any other child of <xsl:stylesheet> or <xsl:transform> in the importing stylesheet. defined xslt, section 2.6.2. gecko support mostly supported with a few issues with top level variables and parameters as of mozilla 1.0. ...
<xsl:sort> - XSLT: Extensible Stylesheet Language Transformations
Web › XSLT › Element › sort
rs are to be ordered first. the allowable values are "upper-first" and "lower-first". lang specifies which language is to be used by the sort. data-type defines whether items are to be ordered alphabetically or numerically. the allowable values are "text" and "number" with "text" being the default. type subinstruction, always appears as a child of <xsl:for-each>, where it must appear before the template proper or of <xsl:apply-templates>. defined xslt, section10. gecko support supported. ...
PI Parameters - XSLT: Extensible Stylesheet Language Transformations
in the xslt-param and xslt-param-namespace pis are parsed using the rules defined in xml-stylesheet. any unrecognized attributes must be ignored. parsing of any attribute must not fail due to the presence of an unrecognized attribute as long as that attribute follows the syntax in xml-stylesheet. both the xslt-param and the xslt-param-namespace pis must appear in the prolog of the document, i.e. before the first element tag. all pis in the prolog must be honored, both ones occurring before and onces occurring after any xml-stylesheet pis. if there are multiple xml-stylesheet pis the parameters apply to all stylesheets as a consequence of that all stylesheets are imported into a single stylesheet per the xslt spec.reference? note that multiple xml-stylesheet xslt pis are not supported in firefo...
An Overview - XSLT: Extensible Stylesheet Language Transformations
ve 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, does not work directly on documents. before transformation can take place, the primary xml document(s) and the stylesheet document(s) must be run through a parser, which creates an abstract representation of the structure of the document in memory. this representation, called the tree, is what is actually manipulated by the processor. the tree is an abstract datatype, a conceptual model which can be implemented in various ways depending on...
The Netscape XSLT/XPath Reference - XSLT: Extensible Stylesheet Language Transformations
ported) lang() (supported) last() (supported) local-name() (supported) name() (supported) namespace-uri() (supported) normalize-space() (supported) not() (supported) number() (supported) position() (supported) round() (supported) starts-with() (supported) string() (supported) string-length() (supported) substring() (supported) substring-after() (supported) substring-before() (supported) sum() (supported) system-property() (supported) translate() (supported) true() (supported) unparsed-entity-url() (not supported) ...
Transforming XML with XSLT - XSLT: Extensible Stylesheet Language Transformations
ed) key() (supported) lang() (supported) last() (supported) local-name() (supported) name() (supported) namespace-uri() (supported) normalize-space() (supported) not() (supported) number() (supported) position() (supported) round() (supported) starts-with() (supported) string() (supported) string-length() (supported) substring() (supported) substring-after() (supported) substring-before() (supported) sum() (supported) system-property() (supported) translate() (supported) true() (supported) unparsed-entity-url() (not supported) for further reading books online the world wide web consortium portals articles tutorials/examples mailing lists/newsgroups resources index original document information copyright information: copyright © 2001-200...
Using the Mozilla JavaScript interface to XSL Transformations - XSLT: Extensible Stylesheet Language Transformations
it has a single parameter, which is the dom node of the xslt stylesheet to import. ...
JavaScript/XSLT Bindings - XSLT: Extensible Stylesheet Language Transformations
javascript/xslt bindings javascript can run xslt transformations through the xsltprocessor object. once instantiated, an xsltprocessor has an xsltprocessor.importstylesheet() method that takes as an argument the xslt stylesheet to be used in the transformation. the stylesheet has to be passed in as an xml document, which means that the .xsl file has to be loaded by the page before calling xsltprocessor.importstylesheet(). this can be done via xmlhttprequest or xmldocument.load(). figure 1 : instantiating an xsltprocessor var xsltprocessor = new xsltprocessor(); // load the xsl file using synchronous (third param is set to false) xmlhttprequest var myxmlhttprequest = new xmlhttprequest(); myxmlhttprequest.open("get", "example.xsl", false); myxmlhttprequest.send(null); var...
Index - WebAssembly
mbly functions are how webassembly functions are represented in javascript. this article describes what they are in a little more detail. 8 index index, webassembly found 12 pages: 9 loading and running webassembly code fetch, javascript, webassembly, xmlhttprequest, bytecode to use webassembly in javascript, you first need to pull your module into memory before compilation/instantiation. this article provides a reference for the different mechanisms that can be used to fetch webassembly bytecode, as well as how to compile/instantiate then run it. 10 understanding webassembly text format functions, javascript, s-expressions, webassembly, calls, memory, shared address, table, text format, was, wasm this finishes our high-level tour of...
Loading and running WebAssembly code - WebAssembly
this article provides a reference for the different mechanisms that can be used to fetch webassembly bytecode, as well as how to compile/instantiate then run it. what are the options? webassembly is not yet integrated with <script type='module'> or es2015 import statements, thus there is not a path to have the browser fetch modules for you using imports. the older webassembly.compile/webassembly.instantiate methods require you to create an arraybuffer containing your webassembly module binary after fetching the raw bytes, and then compile/instantiate it. ...
Compiling from Rust to WebAssembly - WebAssembly
asm-bindgen to communicate between rust and javascript the first part looks like this: use wasm_bindgen::prelude::*; libraries are called "crates" in rust. get it? cargo ships crates. the third line contains a use command, which imports code from a library into your code. in this case, we're importing everything in the wasm_bindgen::prelude module. we use these features in the next section. before we move on to the next section, we should talk a bit more about wasm-bindgen. wasm-pack uses wasm-bindgen, another tool, to provide a bridge between the types of javascript and rust. it allows javascript to call a rust api with a string, or a rust function to catch a javascript exception. we use wasm-bindgen's functionality in our package. in fact, that's the next section. calling external fun...
Converting WebAssembly text format to wasm - WebAssembly
s run with the value (42) provided as a parameter. converting the text .wat into a binary .wasm file let’s have a go at converting the above .wat text representation example into .wasm assembly format. to start with, make a copy 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. go to https://github.com/webassembly/wabt — follow the instructions on this page to set up the tool. once you’ve got the tool built, add the /wabt/out/clang/debug directory to your system path. next, execute the wat...
Compiling an Existing C Module to WebAssembly - WebAssembly
ll the c files and relied on the compiler to strip out everything that was unnecessary. it seemed to work brilliantly: $ emcc -o3 -s wasm=1 -s extra_exported_runtime_methods='["cwrap"]' \ -i libwebp \ webp.c \ libwebp/src/{dec,dsp,demux,enc,mux,utils}/*.c note: this strategy will not work with every c project. many projects rely on autoconf/automake to generate system-specific code before compilation. emscripten provides emconfigure and emmake to wrap these commands and inject the appropriate parameters. you can find more in the emscripten documentation. now you only need some html and javascript to load your new module: <script src="./a.out.js"></script> <script> module.onruntimeinitialized = async _ => { const api = { version: module.cwrap('version', 'number', [])...