Search completed in 0.98 seconds.
927 results for "clear":
Your results are loading. Please wait...
clear - CSS: Cascading Style Sheets
Web › CSS › clear
the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. when applied to non-floating blocks, it moves the border edge of the element down until it is below the margin edge of all relevant floats. the non-floated block's top margin collapses. vertical margins between two floated elements on the other hand will not collapse. ...
... non-floated block's top margin collapses. vertical margins between two floated elements on the other hand will not collapse. when applied to floating elements, the margin edge of the bottom element is moved below the margin edge of all relevant floats. this affects the position of later floats, since later floats cannot be positioned higher than earlier ones. the floats that are relevant to be cleared are the earlier floats within the same block formatting context. if an element contains only floated elements, its height collapses to nothing. if you want it to always be able to resize, so that it contains floating elements inside it, you need to self-clear its children. this is called clearfix, and one way to do it is to add clear to a replaced ::after pseudo-element on it. #container::af...
... block formatting context. if an element contains only floated elements, its height collapses to nothing. if you want it to always be able to resize, so that it contains floating elements inside it, you need to self-clear its children. this is called clearfix, and one way to do it is to add clear to a replaced ::after pseudo-element on it. ...
...And 11 more matches
Clear-Site-Data - HTTP
a directive that does not include the double quotes is invalid. ...
...a directive that does not include the double quotes is invalid. ...
...a directive that does not include the double quotes is invalid. ...
...And 8 more matches
IDBObjectStore.clear() - Web APIs
the clear() method of the idbobjectstore interface creates and immediately returns an idbrequest object, and clears this object store in a separate thread. this is for deleting all the current data out of an object store. clearing an object store consists of removing all records from the object store and removing all records in indexes that reference the object store. to remove only some of the records in a store, use idbobjectstore.delete passing a key or idbkeyrange. note: this feature is available in web workers. syntax var request = objectstore.clear(); returns an idbrequest object on which subsequent events related to this operation are fired. exceptions this method may raise a domexception of one of the following types: exception description readonlyer...
...ptions this method may raise a domexception of one of the following types: exception description readonlyerror the transaction associated with this operation is in read-only mode. transactioninactiveerror this idbobjectstore's transaction is inactive. example in the following code snippet, we open a read/write transaction on our database and clear all the current data out of the object store using clear(). for a full working example, see our to-do notifications app (view example live.) // let us open our database var dbopenrequest = window.indexeddb.open("todolist", 4); dbopenrequest.onsuccess = function(event) { note.innerhtml += '<li>database initialised.</li>'; // store the result of opening the database in the db variable. // ...
... for a full working example, see our to-do notifications app (view example live.) // let us open our database var dbopenrequest = window.indexeddb.open("todolist", 4); dbopenrequest.onsuccess = function(event) { note.innerhtml += '<li>database initialised.</li>'; // store the result of opening the database in the db variable. ...
...And 6 more matches
CanvasRenderingContext2D.clearRect() - Web APIs
the rectangle's corner is at (x, y), and its size is specified by width and height. parameters x the x-axis coordinate of the rectangle's starting point. y the y-axis coordinate of the rectangle's starting point. width the rectangle's width. ...
...the rectangle's corner is at (x, y), and its size is specified by width and height. parameters x the x-axis coordinate of the rectangle's starting point. y the y-axis coordinate of the rectangle's starting point. width the rectangle's width. ...
...the rectangle's corner is at (x, y), and its size is specified by width and height. parameters x the x-axis coordinate of the rectangle's starting point. y the y-axis coordinate of the rectangle's starting point. width the rectangle's width. ...
...And 4 more matches
JS_ClearContextThread
obsolete since jsapi 8this feature is obsolete. although it may still work in some browsers, its use is discouraged since it could be removed at any time. try to avoid using it. transfer a jscontext from one thread to another. syntax jsword js_clearcontextthread(jscontext *cx); jsword js_setcontextthread(jscontext *cx); name type description cx jscontext * the context to transfer from one thread to another. there must not be any active or suspended requests using this context. description an 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 ...
...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. ...
...he 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 looks like this: void mythread(jscontext *cx) { js_setcontextthread(cx); /* note: outside the request */ js_beginrequest(cx); ... js_endrequest(cx); js_clearcontextthread(cx); /* note: outside the request */ } js_setcontextthread ties cx to the current thread for exclusive use. no other thread may use cx until the current thread removes this association by calling js_clearcontextthread. js_setcontextthread returns the thread id of the thread previously associated with this context. when the function is used properly, the return value is always zero...
...And 3 more matches
performance.clearMarks() - Web APIs
// create a small helper to show how many performancemark entries there are. ...
... // create a small helper to show how many performancemark entries there are. ...
... // create a small helper to show how many performancemark entries there are. ...
...And 3 more matches
performance.clearMeasures() - Web APIs
// create a small helper to show how many performancemeasure entries there are. ...
... // create a small helper to show how many performancemeasure entries there are. ...
... // create a small helper to show how many performancemeasure entries there are. ...
...And 3 more matches
Clearing with colors - Web APIs
« previousnext » an example showing how to clear a webgl rendering context to a solid color. clearing the webgl context with a solid color the simplest graphical webgl program. set up the rendering context and then just clear it solid green. note that css sets the background color of the canvas to black, so when the canvas turns green we know that webgl's magic has worked. in addition, you may notice that clearing the drawing buffer with a solid color is a two-stage process. first, we set the clear color to green, using the method clearcolor(). this only changes some internal state of webgl, but does not draw anything yet. next, we actually do the drawing by calling the clear() method. this is typical of how drawing is done with webgl. there is only a handful of methods for ...
...this is why webgl/opengl is often called a state machine. ...
...r to green, using the method clearcolor(). this only changes some internal state of webgl, but does not draw anything yet. next, we actually do the drawing by calling the clear() method. this is typical of how drawing is done with webgl. there is only a handful of methods for actual drawing (clear() is one of them). all other methods are for setting and querying webgl state variables (such as the clear color). there are many "dials" and "switches" that affect drawing with webgl. the clear color is just the first of many you will get to know. this is why webgl/opengl is often called a state machine. ...
...And 3 more matches
DataTransfer.clearData() - Web APIs
the datatransfer.cleardata() method removes the drag operation's drag data for the given type. if data for the given type does not exist, this method does nothing. if this method is called with no arguments or the format is an empty string, the data of all types will be removed. this method does not remove files from the drag operation, so it's possible for there still to be an entry with the type "files" left in the object's datatransfer.types list if there are any files included in the drag. this method can only be used in the handler for the dragstart event, because that's the only time the drag operation's data store is writeable. syntax datatransfer.cleardata([format]); parameters format optional a string which specifies the type of data to remove. if this parameter is an emp...
... html <span class="tweaked" id="source" draggable="true"> select this element, drag it to the drop zone and then release the selection to move the element. ...
...andler); dropable.addeventlistener('dragover', dragoverhandler); dropable.addeventlistener('dragleave', dragleavehandler); dropable.addeventlistener('drop', drophandler); function dragstarthandler (event) { status.innerhtml = 'drag in process'; // change target element's border to signify drag has started event.currenttarget.style.border = '1px dashed blue'; // start by clearing existing clipboards; this will affect all types since we // don't give a specific type. event.datatransfer.cleardata(); // set the drag's format and data (use event target's id for data) event.datatransfer.setdata('text/plain', event.target.id); data.innerhtml = event.datatransfer.getdata('text/plain'); } function dragendhandler (event) { if (!dropped) { s...
...And 2 more matches
performance.clearResourceTimings() - Web APIs
the clearresourcetimings() method removes all performance entries with an entrytype of "resource" from the browser's performance data buffer and sets the size of the performance data buffer to zero. to set the size of the browser's performance data buffer, use the performance.setresourcetimingbuffersize() method. note: this feature is available in web workers. syntax performance.clearresourcetimings(); arguments void return value none this method has no return value. ...
...e data buffer, use the performance.setresourcetimingbuffersize() method. note: this feature is available in web workers. syntax performance.clearresourcetimings(); arguments void return value none this method has no return value. ...
...performance data buff...
...And 2 more matches
WebGL2RenderingContext.clearBuffer[fiuv]() - Web APIs
the webgl2renderingcontext.clearbuffer[fiuv]() methods of the webgl 2 api clear buffers from the currently bound framebuffer. syntax void gl.clearbufferfv(buffer, drawbuffer, values, optional srcoffset); void gl.clearbufferiv(buffer, drawbuffer, values, optional srcoffset); void gl.clearbufferuiv(buffer, drawbuffer, values, optional srcoffset); void gl.clearbufferfi(buffer, drawbuffer, depth, stencil); parameters buffer a glenum specifying the buffer to clear. possible values are: gl.color: color buffer. gl.depth: depth buffer. gl.stencil: stencil buffer. gl.depth_stencil: clears depth and stencil buffers (used with clearbufferfi). drawbuffer a glint specifying the draw buffer to clear. values an array of glint, gluint or glfloat values or an int32array, ui...
...ifying the buffer to clear. possible values are: gl.color: color buffer. gl.depth: depth buffer. gl.stencil: stencil buffer. gl.depth_stencil: clears depth and stencil buffers (used with clearbufferfi). drawbuffer a glint specifying the draw buffer to clear. values an array of glint, gluint or glfloat values or an int32array, uint32array or float32array specifying the values to clear to. depth a glfloat specifying the value to clear a depth render buffer to. stencil a glint specifying the value to clear the stencil render buffer to. return value none. ...
...learbufferfi). drawbuffer a glint specifying the draw buffer to clear. values an array of glint, gluint or glfloat values or an int32array, uint32array or float32array specifying the values to clear to. depth a glfloat specifying the value to clear a depth render buffer to. stencil a glint specifying the value to clear the stencil render buffer to. return value none. ...
...And 2 more matches
WindowOrWorkerGlobalScope.clearTimeout() - Web APIs
however, for clarity, you should avoid doing so. example run the script below in the context of a web page and click on the page once. you'll see a message popping up in a second. if you click the page multiple times in one second, the alert only appears once. ...
...however, for clarity, you should avoid doing so. example run the script below in the context of a web page and click on the page once. you'll see a message popping up in a second. ...
...however, for clarity, you should avoid doing so. example run the script below in the context of a web page and click on the page once. you'll see a message popping up in a second. if you click the page multiple times in one second, the alert only appears once. ...
...And 2 more matches
JS_ClearPendingException
note that a jsapi failure does not necessarily indicate that an exception is pending. ...
...note that a jsapi failure does not necessarily indicate that an exception is pending. ...
... name type description cx jscontext * the context in which the exception was thrown. requires request. in a js_threadsafe build, the caller must be in a request on this jscontext. description js_clearpendingexception cancels the currently pending exception in cx, if any. (there is a pending exception if the most recently thrown exception in cx has not yet been caught or cleared.) when any jsapi call fails with an exception, the caller must either use js_clearpendingexception to catch the exception; or return false to allow the exception to propagate to the caller. note that a jsapi failure does not necessarily indicate that an exception is pending. many jsapi functions can simply report an error and return false without building and throwing an exception object. use j...
...he exception to propagate to the caller. note that a jsapi failure does not necessarily indicate that an exception is pending. ...
MediaSource.clearLiveSeekableRange() - Web APIs
recommendation initial definition. ...
... recommendation initial definition. ...
... recommendation initial definition. ...
... recommendation initial definition. ...
Clearing by clicking - Web APIs
note how we embed the webgl function calls inside the event handler function. ...
... note how we embed the webgl function calls inside the event handler function. ...
... note how we embed the webgl function calls inside the event handler function. ...
...bgl") || canvas.getcontext("experimental-webgl"); if (!gl) { alert("failed to get webgl context.\n" + "your browser or device may not support webgl."); return; } gl.viewport(0, 0, gl.drawingbufferwidth, gl.drawingbufferheight); } // get a random color value using a helper function. var color = getrandomcolor(); // set the clear color to the random color. gl.clearcolor(color[0], color[1], color[2], 1.0); // clear the context with the newly set color. this is // the function call that actually does the drawing. gl.clear(gl.color_buffer_bit); } // random color helper function. function getrandomcolor() { return [math.random(), math.random(), math.random()]; } }, false); the source code of th...
::-ms-clear - Archive of obsolete content
the ::-ms-clear css pseudo-element creates a clear button at the edge of an <input type="text"> text control that clears the current value. this pseudo-element is non-standard, supported only in internet explorer 10, internet explorer 11, and microsoft edge. the clear button is only shown on focused, non-empty text controls. this includes inputs that appear text-like or fall back to type="text". ...
...o type="text". such inputs include: <input type="color"> <input type="date"> <input type="datetime"> <input type="datetime-local"> <input type="email"> <input type="month"> <input type="number"> <input type="search"> <input type="tel"> <input type="time"> <input type="url"> <input type="week"> allowable properties only the following css properties can be used in a rule with ::-ms-clear in its selector. other properties are ignored. -ms-high-contrast-adjust background-clip background-color background-image background-origin background-position-x background-position-y background-repeat background-size border-bottom-color border-bottom-left-radius border-bottom-right-radius border-bottom-style border-bottom-width border-left-color border-left-style border-left-...
...r-top-style border-top-width box-shadow box-sizing color cursor display (values block, inline-block, none) @font-face font-size font-style font-weight height margin-bottom margin-left margin-right margin-top opacity outline-color outline-style outline-width padding-bottom padding-left padding-right padding-top transform transform-origin visibility width syntax ::-ms-clear example html <form> <label for="firstname">first name:</label> <input type="text" id="firstname" name="firstname" placeholder="first name"> <br> <label for="lastname">last name:</label> <input type="text" id="lastname" name="lastname" placeholder="second name"> </form> css input, label { display: block; } input[type=text]::-ms-clear { color: red; /* this sets the cross color ...
StylePropertyMap.clear() - Web APIs
working draft initial definition. ...
... working draft initial definition. ...
... working draft initial definition. ...
WebGLRenderingContext.clear() - Web APIs
the webglrenderingcontext.clear() method of the webgl api clears buffers to preset values. the preset values can be set by clearcolor(), cleardepth() or clearstencil(). the scissor box, dithering, and buffer writemasks can affect the clear() method. syntax void gl.clear(mask); parameters mask a glbitfield bitwise or mask that indicates the buffers to be cleared. possible values are: gl.color_buffer_bit gl.depth_buffer_bit gl.stencil_buffer_bit return value none. exceptions if mask is not one of the listed possible values, a gl.invalid_enum error is thrown. examples the clear() method accepts multiple values. ...
...d. syntax void gl.clear(mask); parameters mask a glbitfield bitwise or mask that indicates the buffers to be cleared. possible values are: gl.color_buffer_bit gl.depth_buffer_bit gl.stencil_buffer_bit return value none. exceptions if mask is not one of the listed possible values, a gl.invalid_enum error is thrown. examples the clear() method accepts multiple values. gl.clear(gl.depth_buffer_bit); gl.clear(gl.depth_buffer_bit | gl.color_buffer_bit); to get the current clear values, query the color_clear_value, depth_clear_value, and stencil_clear_value constants. ...
...turn value none. exceptions if mask is not one of the listed possible values, a gl.invalid_enum error is thrown. examples the clear() method accepts multiple values. gl.clear(gl.depth_buffer_bit); gl.clear(gl.depth_buffer_bit | gl.color_buffer_bit); to get the current clear values, query the color_clear_value, depth_clear_value, and stencil_clear_value constants. gl.getparameter(gl.color_clear_value); gl.getparameter(gl.depth_clear_value); gl.getparameter(gl.stencil_clear_value); specifications specification status comment webgl 1.0the definition of 'clear' in that specification. recommendation initial definition. opengl es 2.0the definition of 'glclear' in that specification. standard man page of the opengl api. ...
WebGLRenderingContext.clearColor() - Web APIs
the webglrenderingcontext.clearcolor() method of the webgl api specifies the color values used when clearing color buffers. this specifies what color values to use when calling the clear() method. the values are clamped between 0 and 1. syntax void gl.clearcolor(red, green, blue, alpha); parameters red a glclampf specifying the red color value used when the color buffers are cleared. default value: 0. green a glclampf specifying the green color value used when the color buffers are cleared. default value: 0. blue a glclampf specifying the blue color value used when the color buffers are cleared. default value: 0. alpha a glclampf specifying the alpha (transparency) value used when the color buffers are cleared. default value: 0. return value none. ...
...ared. default value: 0. green a glclampf specifying the green color value used when the color buffers are cleared. default value: 0. blue a glclampf specifying the blue color value used when the color buffers are cleared. default value: 0. alpha a glclampf specifying the alpha (transparency) value used when the color buffers are cleared. default value: 0. return value none. examples gl.clearcolor(1, 0.5, 0.5, 3); to get the current clear color, query the color_clear_value constant which returns a float32array. gl.getparameter(gl.color_clear_value); // float32array[1, 0.5, 0.5, 1] specifications specification status comment webgl 1.0the definition of 'clearcolor' in that specification. recommendation initial definition. opengl es 2.0the def...
...0.5, 3); to get the current clear color, query the color_clear_value constant which returns a float32array. gl.getparameter(gl.color_clear_value); // float32array[1, 0.5, 0.5, 1] specifications specification status comment webgl 1.0the definition of 'clearcolor' in that specification. recommendation initial definition. opengl es 2.0the definition of 'glclearcolor' in that specification. standard man page of the opengl api. ...
clearResults - Archive of obsolete content
...
... ...
HTMLIFrameElement.clearMatch()
warning: removed in firefox 65. the clearmatch() method of the htmliframeelement clears any content highlighted by findall() or findnext(). invoking this method results in a mozbrowserfindchange event firing, which carries details about the search results. note: use of the browser api requires a privileged app, and browser and/or embed-apps permissions, depending on what you want to do. see using the browser api for more details. syntax instanceofhtmliframeelement.clearmatch(); returns void. parameters none. examples the following function is taken from our browser api demo, and (amongst other things) clears the search results when the search bar is hidden, if an existing search is active. see implementing the search bar for more explanation. searchtoggle.addeventlistener('touc...
...s hidden, if an existing search is active. see implementing the search bar for more explanation. searchtoggle.addeventlistener('touchend',function() { if(search.getattribute('class') === 'search') { search.setattribute('class', 'search shifted'); } else if(search.getattribute('class') === 'search shifted') { search.setattribute('class', 'search'); if(searchactive) { browser.clearmatch(); searchactive = false; prev.disabled = true; next.disabled = true; searchbar.value = ''; } } }); specification not part of any specification. ...
JS_ClearDateCaches
this article covers features introduced in spidermonkey 17 clear the cache of calculated local time from each date object. syntax void js_cleardatecaches(jscontext *cx); name type description cx jscontext * pointer to a javascript context from which to derive runtime information. requires request. in a js_threadsafe build, the caller must be in a request on this jscontext. description js_cleardatecaches clears the cache of calculated local time from each date object. call to propagate a system timezone change. ...
...ype description cx jscontext * pointer to a javascript context from which to derive runtime information. requires request. in a js_threadsafe build, the caller must be in a request on this jscontext. ...
JS_ClearNewbornRoots
obsolete since jsapi 5this feature is obsolete. although it may still work in some browsers, its use is discouraged since it could be removed at any time. try to avoid using it. clear a context's newborn roots, which temporarily protect newly allocated values from garbage collection. syntax void js_clearnewbornroots(jscontext *cx); name 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 glob...
...rnal 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-things, potentially without connecting them to predefined local roots such as *rval or argv[i] in an active jsnative function. using js_enterlocalrootsco...
JS_ClearNonGlobalObject
obsolete since jsapi 34this 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 24 remove all properties associated with an object. ...
...gh 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 24 remove all properties associated with an object. syntax void js_clearnonglobalobject(jscontext *cx, jsobject *obj); name type description cx jscontext * the context in which to clear the object. requires request. in a js_threadsafe build, the caller must be in a request on this jscontext. obj jsobject * object from which to delete all properties. description js_clearnonglobalobject removes all of obj's own properties, except the special __proto__ and __parent__ properties, in a single operation. properties belonging to objects on obj's prototype chain are...
JS_ClearRegExpStatics
clear the pending regexp input and flags. syntax bool js_clearregexpstatics(jscontext *cx, handleobject obj); name type description cx jscontext * the context. requires request. in a js_threadsafe build, the caller must be in a request on this jscontext. obj js::handleobject a pointer to a global object. description js_clearregexpstatics clears the pending input string and flags of the built-in regexp object. on successful, js_clearregexpstatics returns true, otherwise returns false. ...
...context. requires request. in a js_threadsafe build, the caller must be in a request on this jscontext. obj js::handleobject a pointer to a global object. description js_clearregexpstatics clears the pending input string and flags of the built-in regexp object. ...
JS_ClearScope
obsolete since jsapi 18this feature is obsolete. although it may still work in some browsers, its use is discouraged since it could be removed at any time. try to avoid using it. remove all properties associated with an object. syntax void js_clearscope(jscontext *cx, jsobject *obj); name type description cx jscontext * the context in which to clear the object. requires request. in a js_threadsafe build, the caller must be in a request on this jscontext. obj jsobject * object from which to delete all properties. description js_clearscope removes all of obj's own properties, except the special __proto__ and __parent__ properties, in a single operation. properties belonging to objects on obj's prototype chain are not affected. to remove a s...
...escription js_clearscope removes all of obj's own properties, except the special __proto__ and __parent__ properties, in a single operation. properties belonging to objects on obj's prototype chain are not affected. to remove a single property from an object, use js_deleteproperty. to remove a single array object element, use js_deleteelement. ...
DataTransfer.mozClearDataAt() - Web APIs
the datatransfer.mozcleardataat() method removes the data associated with the given format for an item at the specified index. the index must be in the range from zero to the number of items minus one. if the format argument is not provided, then the data associated with all formats is removed. if the format is not found, then this method has no effect. if the last format for the item is removed, the entire item is removed, reducing mozitemcount by one. removing the last format for a particular index removes that item entirely, shifting the remaining items down and changing their indices. note: this method is gecko-specific. syntax void datatransfer.mozcleardataat([type], index); arguments type a string representing the type of the drag data to remove from the drag data object. ...
...g the remaining items down and changing their indices. note: this method is gecko-specific. syntax void datatransfer.mozcleardataat([type], index); arguments type a string representing the type of the drag data to remove from the drag data object. index a unsigned long representing the index of the data to remove. return value void example this example shows the use of the mozcleardataat() method in a dragend event handler. function dragend_handler(event) { var dt = event.datatransfer; // remove a text/html item dt.mozcleardataat("text/html", 1); } specifications this method is not defined in any web standard. ...
DataTransferItemList.clear() - Web APIs
the datatransferitemlist method clear() removes all datatransferitem objects from the drag data items list, leaving the list empty. the drag data store in which this list is kept is only writable while handling the dragstart event. while handling drop, the drag data store is in read-only mode, and this method silently does nothing. no exception is thrown. syntax datatransferitemlist.clear(); parameters none. return value undefined example this example shows the use of the clear() method. html <div> <p id="source" ondragstart="dragstart_handler(event);" ondragend="dragend_handler(event);" draggable="true"> select this element, drag it to the drop zone and then release the selection to move the element.</p> </div> <div id="target" ondrop="drop_handler(event);" ondra...
... console.log("... drop: uri = " + s); }); } } } function dragover_handler(ev) { console.log("dragover"); ev.preventdefault(); // set the dropeffect to move ev.datatransfer.dropeffect = "move" } function dragend_handler(ev) { console.log("dragend"); var datalist = ev.datatransfer.items; for (var i = 0; i < datalist.length; i++) { datalist.remove(i); } // clear any remaining drag data datalist.clear(); } result result link specifications specification status comment html living standardthe definition of 'clear()' in that specification. living standard html 5.1the definition of 'clear()' in that specification. recommendation not included in w3c html5 recommendation ...
Document.clear() - Web APIs
Web › API › Document › clear
the document.clear() method clears the whole specified document in early (pre-1.0) versions of mozilla. in recent versions of mozilla-based applications, as well as in internet explorer and netscape 4, this method does nothing. ...
... the document.clear() method clears the whole specified document in early (pre-1.0) versions of mozilla. in recent versions of mozilla-based applications, as well as in internet explorer and netscape 4, this method does nothing. ...
Geolocation.clearWatch() - Web APIs
the geolocation.clearwatch() method is used to unregister location/error monitoring handlers previously installed using geolocation.watchposition(). syntax navigator.geolocation.clearwatch(id); parameters id the id number returned by the geolocation.watchposition() method when installing the handler you wish to remove. ...
...ion.clearwatch(id); parameters id the id number returned by the geolocation.watchposition() method when installing the handler you wish to remove. ...
USBDevice.clearHalt() - Web APIs
the clearhalt() method of the usbdevice interface returns a promise that resolves when a halt condition is cleared. a halt condition is when a data tranfer to or from the device has a status of 'stall', which requires the web page (the host system, in usb terminology) to clear that condition. see the for details. syntax var promise = usbdevice.clearhalt(direction, endpointnumber) parameters direction indicates whether the devices input or output should be cleared. valid values are 'in' or 'out'. endpointnumber indicates the number of the endpoint to clear. the promise will reject if an invalid endpoint is supplied. return value a promise. example the following example shows how to test for and clear a 'stall' condition in the result of a data transfer. what data can be pass...
...lar and unique to each device. while (true) { let result = await data.transferin(1, 6); if (result.data && result.data.bytelength === 6) { console.log('channel 1: ' + result.data.getuint16(0)); console.log('channel 2: ' + result.data.getuint16(2)); console.log('channel 5: ' + result.data.getuint16(4)); } if (result.status === 'stall') { console.warn('endpoint stalled. clearing.'); await device.clearhalt('in', 1); } } specifications specification status comment webusbthe definition of 'clearhalt()' in that specification. draft initial definition. ...
WebGLRenderingContext.clearDepth() - Web APIs
the webglrenderingcontext.cleardepth() method of the webgl api specifies the clear value for the depth buffer. this specifies what depth value to use when calling the clear() method. the value is clamped between 0 and 1. syntax void gl.cleardepth(depth); parameters depth a glclampf specifying the depth value used when the depth buffer is cleared. default value: 1. return value none. examples gl.cleardepth(0.5); to get the current depth clear value, query the depth_clear_value constant. gl.getparameter(gl.depth_clear_value); // 0.5 specifications specification status comment webgl 1.0the definition of 'cleardepth' in that specification. recommendation initial definition. ...
...: 1. return value none. examples gl.cleardepth(0.5); to get the current depth clear value, query the depth_clear_value constant. gl.getparameter(gl.depth_clear_value); // 0.5 specifications specification status comment webgl 1.0the definition of 'cleardepth' in that specification. recommendation initial definition. opengl es 2.0the definition of 'glcleardepthf' in that specification. standard man page of the opengl api. ...
WindowOrWorkerGlobalScope.clearInterval() - Web APIs
the clearinterval() method of the windoworworkerglobalscope mixin cancels a timed, repeating action which was previously established by a call to setinterval(). syntax scope.clearinterval(intervalid) parameters intervalid the identifier of the repeated action you want to cancel. this id was returned by the corresponding call to setinterval(). it's worth noting that the pool of ids used by setinterval() and settimeout() are shared, which means you can technically use clearinterval() and cleartimeout() interchangeably. however, for clarity, you should avoid doing so. return value undefined example see the setinterval() examples. ...
...ol of ids used by setinterval() and settimeout() are shared, which means you can technically use clearinterval() and cleartimeout() interchangeably. however, for clarity, you should avoid doing so. return value undefined example see the setinterval() examples. specifications specification status comment html living standardthe definition of 'windoworworkerglobalscope.clearinterval()' in that specification. living standard method moved to the windoworworkerglobalscope mixin in the latest spec. html living standardthe definition of 'clearinterval()' in that specification. living standard ...
clearSelection - Archive of obsolete content
a select event is sent before the items are deselected. ...
PR_ClearInterrupt
clears the interrupt request for the calling thread. syntax #include <prthread.h> void pr_clearinterrupt(void); description interrupting is a cooperative process, so it's possible that the thread passed to pr_interrupt may never respond to the interrupt request. for example, the target thread may reach the agreed-on control point without providing an opportunity for the runtime to notify the thread of the interrupt request. in this case, the request for interrupt is still pending with the thread and must be explicitly canceled. therefore it is sometimes necessary to call pr_clearinterrupt to clear a previous interrupt request. if no interrupt request is pending, pr_clearinterrupt is a no-op. ...
CanvasRenderingContext2D.clearHitRegions() - Web APIs
the canvasrenderingcontext2d method clearhitregions() removes all hit regions from the canvas. syntax void ctx.clearhitregions(); examples using the clearhitregions method this example demonstrates the clearhitregions() method. html <canvas id="canvas"></canvas> javascript const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); // set some hit regions ctx.addhitregion({id: 'eyes'}); ctx.addhitregion({id: 'nose'}); ctx.addhitregion({id: 'mouth'}); // remove them altogether from the canvas ctx.clearhitregions(); specifications canvas hit regions have been removed from the whatwg living standard, although discussions about future standardization are ongoing. see https://github.com/whatwg/html/issues/3407 for more information. ...
console.clear() - Web APIs
Web › API › Console › clear
the console.clear() method clears the console if the environment allows it. syntax console.clear(); specifications specification status comment console apithe definition of 'console.clear()' in that specification. living standard initial definition ...
msClearEffects - Web APIs
non-standard this feature is non-standard and is not on a standards track. do not use it on production sites facing the web: it will not work for every user. there may also be large incompatibilities between implementations and the behavior may change in the future. the mscleareffects method of the htmlmediaelement, is a proprietary method specific to internet explorer and microsoft edge. mscleareffects clears all effects from the media pipeline. syntax htmlmediaelement.mscleareffects(); parameters this method has no parameters. return value this method does not return a value. see also touch api microsoft api extensions ...
Storage.clear() - Web APIs
Web › API › Storage › clear
the clear() method of the storage interface clears all keys stored in a given storage object. syntax storage.clear(); return value undefined. examples the following function creates three data entries in local storage, and then deletes them by using clear(). function populatestorage() { localstorage.setitem('bgcolor', 'red'); localstorage.setitem('font', 'helvetica'); localstorage.setitem('image', 'migato.png'); localstorage.clear(); } note: for a real world example, see our web storage demo. specifications specification status comment html living standardthe definition of 'storage.clear' in that specification. living standard ...
WebGLRenderingContext.clearStencil() - Web APIs
the webglrenderingcontext.clearstencil() method of the webgl api specifies the clear value for the stencil buffer. this specifies what stencil value to use when calling the clear() method. syntax void gl.clearstencil(s); parameters s a glint specifying the index used when the stencil buffer is cleared. default value: 0. return value none. examples gl.clearstencil(1); to get the current stencil clear value, query the stencil_clear_value constant. gl.getparameter(gl.stencil_clear_value); // 1 specifications specification status comment webgl 1.0the definition of 'clearstencil' in that specification. recommendation initial definition. opengl es 2.0the definition of 'glclearstencil' in that specification. standard man page of the open...
Window.clearImmediate() - Web APIs
this method clears the action specified by window.setimmediate. this method is not expected to become standard, and is only implemented by recent builds of internet explorer and node.js 0.10+. it meets resistance both from gecko (firefox) and webkit (google/apple). syntax window.clearimmediate( immediateid ) where immediateid is a id returned by window.setimmediate. examples let immediateid = setimmediate(() => { // run some code } document.getelementbyid("button") .addeventlistener(() => { clearimmediate(immediateid); }); specifications specification status comment efficient script yielding the definition of 'setimmediate' in that specification. editor's draft initial definition. ...
Map.prototype.clear() - JavaScript
the clear() method removes all elements from a map object. the source for this interactive example is stored in a github repository. if you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. syntax mymap.clear(); return value undefined. examples using clear() var mymap = new map(); mymap.set('bar', 'baz'); mymap.set(1, 'foo'); mymap.size; // 2 mymap.has('bar'); // true mymap.clear(); mymap.size; // 0 mymap.has('bar') // false specifications specification ecmascript (ecma-262)the definition of 'map.prototype.clear' in that specification. ...
Set.prototype.clear() - JavaScript
the clear() method removes all elements from a set object. the source for this interactive example is stored in a github repository. if 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 myset.clear(); return value undefined. examples using the clear method var myset = new set(); myset.add(1); myset.add('foo'); myset.size; // 2 myset.has('foo'); // true myset.clear(); myset.size; // 0 myset.has('bar') // false specifications specification ecmascript (ecma-262)the definition of 'set.prototype.clear' in that specification. ...
WeakMap.prototype.clear() - JavaScript
the clear() method used to remove all elements from a weakmap object, but is no longer part of ecmascript and its implementations. syntax wm.clear(); examples using the clear method var wm = new weakmap(); var obj = {}; wm.set(obj, 'foo'); wm.set(window, 'bar'); wm.has(obj); // true wm.has(window); // true wm.clear(); wm.has(obj) // false wm.has(window) // false specifications not part of any standard. ...
WeakSet.prototype.clear() - JavaScript
the clear() method used to remove all elements from a weakset object, but is no longer part of ecmascript and its implementations. syntax ws.clear(); examples using the clear method var ws = new weakset(); ws.add(window); ws.has(window); // true ws.clear(); ws.has(window); // false specifications not part of any standard. ...
Index - Web APIs
Web › API › Index
animation() api, animation, animations, constructor, experimental, reference, web animations api the animation() constructor of the web animations api returns a new animation object instance. 64 animation.cancel() api, animation, method, reference, web animations, cancel, waapi, web animations api the web animations api's cancel() method of the animation interface clears all keyframeeffects caused by this animation and aborts its playback. 65 animation.currenttime api, animation, animations, property, reference, web animations, web animations api the animation.currenttime property of the web animations api returns and sets the current time value of the animation in milliseconds, whether running or paused. 66 animation.effect a...
...sualization, photo manipulation, and real-time video processing. 517 a basic ray-caster advanced, canvas, example, graphics, html, web 518 canvas tutorial canvas, graphics, guide, html, html5, intermediate, web this tutorial describes how to use the <canvas> element to draw 2d graphics, starting with the basics. the examples provided should give you some clear ideas what you can do with canvas, and will provide code snippets that may get you started in building your own content. 519 advanced animations canvas, graphics, tutorial we are going to use a ball for our animation studies, so let's first draw that ball onto the canvas. the following code will set us up. 520 applying styles and colors canvas, graphics, html, ...
...wn, 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. 522 basic usage of canvas canvas, graphics, html, intermediate, tutorial at first sight a <canvas> looks like the <img> element, with the only clear difference being that it doesn't have the src and alt attributes. indeed, the <canvas> element has only two attributes, width and height. these are both optional and can also be set using dom properties. when no width and height attributes are specified, the canvas will initially be 300 pixels wide and 150 pixels high. the element can be sized arbitrarily by css, but during rendering the image is...
...And 39 more matches
Floats - Learn web development
ost commonly used tools for creating multiple column layouts on webpages. with the advent of flexbox and grid it has now returned to its original purpose, as this article explains. prerequisites: html basics (study introduction to html), and an idea of how css works (study introduction to css.) objective: to learn how to create floated features on webpages, and to use the clear property and other methods of clearing floats. the background of floats the float property was introduced to allow web developers to implement simple layouts involving an image floating inside a column of text, with the text wrapping around the left or right of it. the kind of thing you might get in a newspaper layout. but web developers quickly realized that you can float anything, not ...
...idth: 150px; height: 150px; border-radius: 5px; background-color: rgb(207,232,220); padding: 1em; } .special { background-color: rgb(79,185,227); padding: 10px; color: #fff; } the line boxes of our following element have been shortened so the text runs around the float, but due to the float being removed from normal flow the box around the paragraph still remains full width. ...
...he line boxes of our following element have been shortened so the text runs around the float, but due to the float being removed from normal flow the box around the paragraph still remains full width. clearing floats we have seen that the float is removed from normal flow and that other elements will display beside it, therefore if we want to stop the following element from moving up we need to clear it; this is achieved with the clear property. in your html from the previous example, add a class of cleared to the second paragraph below the floated item. then add the following to your css: .cleared { clear: left; } float example 3 <h1>simple float example</h1> <div class="box">float</div> <p class="special">lorem ipsum dolor sit amet, consectetur adipiscing elit. nulla luctus aliqu...
...And 14 more matches
Chapter 5: Let's build a Firefox extension - Archive of obsolete content
eferences it may happen your extension displays some useful messages such as alerts to the user. though they are nested in javascript, the strings should be localized too, for the sake of ui consistency. suppose you have these strings nested in a .js file: if ( password == userpassword ) { oprefs.setboolpref("access.authenticated", true); } else { alert ("invalid password"); ...... function clear() { sure = confirm("are you sure?"); first, you have to find or create a myextension.properties file in your locale folder (notice: always stick to utf-8). then you simply write variable names and the sentences or words that should appear to the final user. something like : wrongpassmessage=invalid password areyousuremessage=are you sure? (where invalid password and are you sure? are the str...
...because we’ve changed the chrome manifest, we need to relaunch firefox once, as discussed in the part “operations checks on revised source files”. so relaunch firefox and display the clock window to make sure it is working correctly. then type about:config into...
...xtension in this section, we will create an extension that uses a new feature: the session store api. this will allow the user to save and restore session snapshots (browser window states) at any time. phase 1: test install figure 12 shows what the interface for the session-management extension will look like. under the tool menu, the session store submenu contains two items—save session and clear sessions; in between them is a list of previously saved sessions that you can restore, most recent first. fixme: figure 12: session-management extension interface: the menu as discussed in the part “the session store api”, sessions are represented as json character strings. sessions are stored in a subdirectory of the profile directory (called “sessionstore”), with each session stored a...
...And 11 more matches
Cooperative asynchronous JavaScript: Timeouts and intervals - Learn web development
= settimeout(sayhi, 2000); that can be useful if you have a function that needs to be called both from a timeout and in response to an event, for example. but it can also just help keep your code tidy, especially if the timeout callback is more than a few lines of code. settimeout() returns an identifier value that can be used to refer to the timeout later, such as when you want to stop it. see clearing timeouts (below) to learn how to do that. passing parameters to a settimeout() function any parameters that you want to pass to the function being run inside the settimeout() must be passed to it as additional parameters at the end of the list. for example, you could refactor the previous function so that it will say hi to whatever person's name is passed to it: function sayhi(who) { ale...
...eout() must be passed to it as additional parameters at the end of the list. for example, you could refactor the previous function so that it will say hi to whatever person's name is passed to it: function sayhi(who) { alert(`hello ${who}!`); } now, you can pass the name of the person into the settimeout() call as a third parameter: let mygreeting = settimeout(sayhi, 2000, 'mr. ...
...ction so that it will say hi to whatever person's name is passed to it: function sayhi(who) { alert(`hello ${who}!`); } now, you can pass the name of the person into the settimeout() call as a third parameter: let mygreeting = settimeout(sayhi, 2000, 'mr. universe'); clearing timeouts finally, if a timeout has been created, you can cancel it before the specified time has elapsed by calling cleartimeout(), passing it the identifier of the settimeout() call as a parameter. so to cancel our above timeout, you'd do this: cleartimeout(mygreeting); note: see greeter-app.html for a slightly more involved demo that allows you to set the name of the person to say hello to in a form, and cancel the greeting using a separate button (see the source code also). setinterval() settimeout() works ...
...And 10 more matches
Index
96 js_checkaccess jsapi reference, spidermonkey check whether a running script may access a given object property. 197 js_checkforinterrupt jsapi_reference, reference, référence(2), spidermonkey js_checkforinterrupt checks for the interrupt, and handle it if it's pending. js_checkforinterrupt returns false if interrupt callback returns false. ...
...y. 197 js_checkforinterrupt jsapi_reference, reference, référence(2), spidermonkey js_checkforinterrupt checks for the interrupt, and handle it if it's pending. js_checkforinterrupt returns false if interrupt callback returns false. 198 js_clearcontextthread jsapi reference, spidermonkey transfer a jscontext from one thread to another. ...
... js_checkforinterrupt checks for the interrupt, and handle it if it's pending. js_checkforinterrupt returns false if interrupt callback returns false. 198 js_clearcontextthread jsapi reference, spidermonkey transfer a jscontext from one thread to another. 199 js_cleardatecaches date, jsapi reference, javascript, reference, référence(2), spidermonkey js_cleardatecaches clears the cache of calculated local time from each date object. call to propagate a system timezone change. ...
...And 8 more matches
WindowOrWorkerGlobalScope.setInterval() - Web APIs
this method is defined by the windoworworkerglobalscope mixin. ...
...ents to setinterval() in the first syntax does not work in internet explorer 9 and earlier. if you want to enable this functionality on that browser, you must use a polyfill (see the callback arguments section). return value the returned intervalid is a numeric, non-zero value which identifies the timer created by the call to setinterval(); this value can be passed to windoworworkerglobalscope.clearinterval() to cancel the timeout. it may be helpful to be aware that setinterval() and settimeout() share the same pool of ids, and that clearinterval() and cleartimeout() can technically be used interchangeably. for clarity, however, you should try to always match them to avoid confusion when maintaining your code. note: the delay argument is converted to a signed 32-bit integer. this effective...
...ow.setinterval(mycallback, 500, 'parameter 1', 'parameter 2'); function mycallback(a, b) { // your code here // parameters are purely optional. console.log(a); console.log(b); } example 2: alternating two colors the following example calls the flashtext() function once a second until the stop button is pressed. <!doctype html> <html> <head> <meta charset="utf-8" /> <title>setinterval/clearinterval example</title> <script> var nintervid; function changecolor() { nintervid = setinterval(flashtext, 1000); } function flashtext() { var oelem = document.getelementbyid('my_box'); oelem.style.color = oelem.style.color == 'red' ? 'blue' : 'red'; // oelem.style.color == 'red' ? 'blue' : 'red' is a conditional or ternary operator. } functi...
...And 8 more matches
Fundamental text and font styling - Learn web development
of an element's text), or ::selection (selects the text currently highlighted by the cursor.) fonts let's move straight on to look at properties for styling fonts. in this example we'll apply some different css properties to the same html sample, which looks like this: <h1>tommy the cat</h1> <p>well i remember it as though it were a meal ago...</p> <p>said tommy the cat as he reeled back to clear whatever foreign matter may have nestled its way into his mighty throat. many a fat alley rat had met its demise while staring point blank down the cavernous barrel of this awesome prowling machine. truly a wonder of nature this urban predator — tommy the cat had many a story to tell. but it was a rare occasion such as this that he did.</p> you can find the finished example on github (see al...
...er things, such as an underline or overline placed on text using the text-decoration property). color can accept any css color unit, for example: p { color: red; } this will cause the paragraphs to become red, rather than the standard browser default black, like so: <h1>tommy the cat</h1> <p>well i remember it as though it were a meal ago...</p> <p>said tommy the cat as he reeled back to clear whatever foreign matter may have nestled its way into his mighty throat. many a fat alley rat had met its demise while staring point blank down the cavernous barrel of this awesome prowling machine. truly a wonder of nature this urban predator — tommy the cat had many a story to tell. but it was a rare occasion such as this that he did.</p> font families to set a different font on your t...
...ms — need to be surrounded by quotes, for example "trebuchet ms". a font-family example let's add to our previous example, giving the paragraphs a sans-serif font: p { color: red; font-family: helvetica, arial, sans-serif; } this gives us the following result: <h1>tommy the cat</h1> <p>well i remember it as though it were a meal ago...</p> <p>said tommy the cat as he reeled back to clear whatever foreign matter may have nestled its way into his mighty throat. many a fat alley rat had met its demise while staring point blank down the cavernous barrel of this awesome prowling machine. truly a wonder of nature this urban predator — tommy the cat had many a story to tell. but it was a rare occasion such as this that he did.</p> font size in our previous module's css values a...
...And 6 more matches
Video and Audio APIs - Learn web development
first of all, add the following two addeventlistener() lines below the previous ones: rwd.addeventlistener('click', mediabackward); fwd.addeventlistener('click', mediaforward); now on to the event handler functions — add the following code below your previous functions to define mediabackward() and mediaforward(): let intervalfwd; let intervalrwd; function mediabackward() { clearinterval(intervalfwd); fwd.classlist.remove('active'); if(rwd.classlist.contains('active')) { rwd.classlist.remove('active'); clearinterval(intervalrwd); media.play(); } else { rwd.classlist.add('active'); media.pause(); intervalrwd = setinterval(windbackward, 200); } } function mediaforward() { clearinterval(intervalrwd); rwd.classlist.remove('active'); if...
...contains('active')) { rwd.classlist.remove('active'); clearinterval(intervalrwd); media.play(); } else { rwd.classlist.add('active'); media.pause(); intervalrwd = setinterval(windbackward, 200); } } function mediaforward() { clearinterval(intervalrwd); rwd.classlist.remove('active'); if(fwd.classlist.contains('active')) { fwd.classlist.remove('active'); clearinterval(intervalfwd); media.play(); } else { fwd.classlist.add('active'); media.pause(); intervalfwd = setinterval(windforward, 200); } } you'll notice that first we initialize two variables — intervalfwd and intervalrwd — you'll find out what they are for later on. let's step through mediabackward() (the functionality for mediaforward() is exactly the same, but in ...
...); media.play(); } else { fwd.classlist.add('active'); media.pause(); intervalfwd = setinterval(windforward, 200); } } you'll notice that first we initialize two variables — intervalfwd and intervalrwd — you'll find out what they are for later on. let's step through mediabackward() (the functionality for mediaforward() is exactly the same, but in reverse): we clear any classes and intervals that are set on the fast forward functionality — we do this because if we press the rwd button after pressing the fwd button, we want to cancel any fast forward functionality and replace it with the rewind functionality. if we tried to do both at one, the player would break. we use an if statement to check whether the active class has been set on the rwd button, ind...
...And 6 more matches
Scissor animation - Web APIs
« previousnext » a simple webgl example in which we have some animation fun using scissoring and clearing operations. animation with scissoring in this example, we are animating squares using scissor() and clear(). we again establish an animation loop using timers. note that this time it is the position of the square (the scissoring area) that is updated every frame (we set frame rate to roughly one every 17ms, or roughly 60fps – frames per second). in contrast, the color of the square (set with clearcolor) is only updated when a new square is created. this is a nice demonstration of webgl as a state machine. ...
... square (the scissoring area) that is updated every frame (we set frame rate to roughly one every 17ms, or roughly 60fps – frames per second). in contrast, the color of the square (set with clearcolor) is only updated when a new square is created. this is a nice demonstration of webgl as a state machine. for each square, we set its color once, and then update only its position every frame. the clear color state of webgl remains at the set value, until we change it again when a new square is created. ...
...r second). in contrast, the color of the square (set with clearcolor) is only updated when a new square is created. this is a nice demonstration of webgl as a state machine. for each square, we set its color once, and then update only its position every frame. the clear color state of webgl remains at the set value, until we change it again when a new square is created. ...
...And 6 more matches
Ember Interactivity: Footer functionality, conditional rendering - Learn web development
previous overview: client-side javascript frameworks next now it's time to start tackling the footer functionality in our app. here we'll get the todo counter to update to show the correct number of todos still to complete, and correctly apply styling to completed todos (i.e. where the checkbox has been checked). we'll also wire up our "clear completed" button. along the way, we'll learn about using conditional rendering in our templates. prerequisites: at minimum, it is recommended that you are familiar with the core html, css, and javascript languages, and have knowledge of the terminal/command line. a deeper understanding of modern javascript features (such as classes, modules, etc), will be extremely beneficial, as ember makes heavy use of them. ...
...of them. objective: to continue our learning about components classes, start looking at conditional rendering, and wire up some of our footer functionality. connecting the behavior in the footer to get the footer working, we need to implement the following thre areas of functionality: a pending todo counter. filters for all, active, and completed todos. a button to clear the completed todos. because we need access to our service from the footer component, we need to generate a class for the footer. enter the following terminal command to do so: ember generate component-class footer next, go and find the newly-created todomvc/app/components/footer.js file and update it to the following: import component from '@glimmer/component'; import { inject...
... in todo-data.js, add the following getter underneath the existing all() getter to define what the incomplete todos actually are: get incomplete() { return this.todos.filter(todo => { return todo.iscompleted === false; }); } using array.filter(), we declare that "incomplete" todos ar...
...And 5 more matches
sslfnc.html
he initialization functions that are specific to ssl. for a complete list of nss initialization functions, see initialization. note that at least one of the functions listed in ssl export policy functions must also be called during nss initialization. nss_init nss_initreadwrite nss_nodb_init ssl_optionsetdefault ssl_optiongetdefault ssl_cipherprefsetdefault ssl_cipherprefgetdefault ssl_clearsessioncache ssl_configserversessionidcache ssl_configmpserversidcache ssl_inheritmpserversidcache nss_init sets up configuration files and performs other tasks required to run network security services. database files are opened read-only. syntax #include "nss.h" secstatus nss_init(char *configdir); parameter this function has the following parameter: confi...
...uccessful, secfailure. use pr_geterror to obtain error code. description ssl_cipherprefgetdefault performs the complementary function to ssl_cipherprefsetdefault. it returns the application process' current default preference value for the specified cipher suite. if the application has not previously set the default preference, ssl_cipherprefgetdefault returns the factory setting. ssl_clearsessioncache empties the ssl client session id cache. syntax #include "ssl.h" void ssl_clearsessioncache(void); description you must call ssl_clearsessioncache after you use one of the ssl export policy functions to change cipher suite policy settings or use ssl_cipherprefsetdefault to enable or disable any cipher suite. otherwise, the old settings remain in the session cache and wi...
... syntax #include "ssl.h" void ssl_clearsessioncache(void); description you must call ssl_clearsessioncache after you use one of the ssl export policy functions to change cipher suite policy settings or use ssl_cipherprefsetdefault to enable or disable any cipher suite. otherwise, the old settings remain in the session cache and will be used instead of the new settings. this function clears only the client cache. the client cache is not configurable. it is located in ram (not on disk), and has the following characteristics: maximum number of entries: unlimited ssl 2.0 timeout value: 100 seconds ssl 3.0 timeout value: 24 hours note: if an ssl client application does not call ssl_clearsessioncache before shutdown, nss_shutdown fails with the error code sec_error_busy. ss...
...And 5 more matches
WebIDL bindings
nction implementation by the interface developer. maplike example interface: interface stringtolongmap { maplike<domstring, long>; }; the bindings for this interface will generate the storage structure for the map, as well as helper functions for accessing that structure from c++. ...
... namespace maplikehelpers } // namespace stringtolongmapbindings setlike example interface: interface stringset { setlike<domstring>; }; the bindings for this interface will generate the storage structure for the set, as well as helper functions for accessing that structure from c++. ...
...otten very quickly from the js object by the jit. such attributes will have their getter called immediately when the js wrapper for the dom object is created, and the returned value will be stored directly on the js object. later gets of the attribute will not call the c++ getter and instead use the cached value. if the value returned by the attribute needs to change, the c++ code should call the clearcachedfoovalue method in the namespace of the relevant binding, where foo is the name of the attribute. this will immediately call the c++ getter and cache the value it returns, so it needs a jscontext to work on. this extended attribute can only be used in on attributes whose getters are [pure] or [constant] and which are not [throws] or [getterthrows]. so for example, given this idl: interface...
...And 5 more matches
Advanced animations - Web APIs
ial here, the ball is actually a simple circle and gets drawn with the help of the arc() method. adding velocity now that we have a ball, we are ready to add a basic animation like we have learned in the last chapter of this tutorial. again, window.requestanimationframe() helps us to control the animation. the ball gets moving by adding a velocity vector to the position. for each frame, we also clear the canvas to remove old circles from prior frames. var canvas = document.getelementbyid('canvas'); var ctx = canvas.getcontext('2d'); var raf; var ball = { x: 100, y: 100, vx: 5, vy: 2, radius: 25, color: 'blue', draw: function() { ctx.beginpath(); ctx.arc(this.x, this.y, this.radius, 0, math.pi * 2, true); ctx.closepath(); ctx.fillstyle = this.color; ctx.fill...
...om prior frames. ...
...="300"></canvas> var canvas = document.getelementbyid('canvas'); var ctx = canvas.getcontext('2d'); var raf; var ball = { x: 100, y: 100, vx: 5, vy: 2, radius: 25, color: 'blue', draw: function() { ctx.beginpath(); ctx.arc(this.x, this.y, this.radius, 0, math.pi * 2, true); ctx.closepath(); ctx.fillstyle = this.color; ctx.fill(); } }; function draw() { ctx.clearrect(0,0, canvas.width, canvas.height); ball.draw(); ball.x += ball.vx; ball.y += ball.vy; if (ball.y + ball.vy > canvas.height || ball.y + ball.vy < 0) { ball.vy = -ball.vy; } if (ball.x + ball.vx > canvas.width || ball.x + ball.vx < 0) { ball.vx = -ball.vx; } raf = window.requestanimationframe(draw); } canvas.addeventlistener('mouseover', function(e) { ra...
...And 5 more matches
Taking still photos with WebRTC - Web APIs
re(); ev.preventdefault(); }, false); this method is simple enough: it just calls our takepicture() function, defined below in the section capturing a frame from the stream, then calls event.preventdefault() on the received event to prevent the click from being handled more than once. ...
...); this method is simple enough: it just calls our takepicture() function, defined below in the section capturing a frame from the stream, then calls event.preventdefault() on the received event to prevent the click from being handled more than once. ...
...picture() function, defined below in the section capturing a frame from the stream, then calls event.preventdefault() on the received event to prevent the click from being handled more than once. wrapping up the startup() method there are only two more lines of code in the startup() method: clearphoto(); } this is where we call the clearphoto() method we'll describe below in the section clearing the photo box. ...
...And 5 more matches
How to convert an overlay extension to restartless - Archive of obsolete content
nternal jar anymore. firefox aggressively caches add-on data a bit too much. your restartless add-on won't actually reload some types of files if they are in a jar and the add-on is updated without a restart. the big culprits are jsm files and locale files (namely property files), though in some situations this is true for dynamically loaded image files too. you're still going to have to manually clear the chrome cache on add-on shutdown to work around this, but that doesn't seem to be enough with an internal jar. so, time to switch to extractionless, too. see here for the list of stuff you can't have in addition to no resource:// uris or file:// uris to files inside your xpi. if you actually can't find a way to go fully extractionless, you could hack together some combination of internal jar(...
...utdown(data,reason) { if (reason == app_shutdown) return; foreachopenwindow(unloadfromwindow); services.wm.removelistener(windowlistener); mymodule.shutdown(); // do whatever shutdown stuff you need to do on addon disable components.utils.unload("chrome://myaddon/content/mymodule.jsm"); // same url as above // hack warning: the addon manager does not properly clear all addon related caches on update; // in order to fully update images and locales, their caches need clearing here services.obs.notifyobservers(null, "chrome-flush-caches", null); } function install(data,reason) { } function uninstall(data,reason) { } function loadintowindow(window) { /* call/move your ui construction function here */ } function unloadfromwindow(window) { /...
... regular "unload" event comes in. step 10: bypass cache when loading properties files the above will get you a working add-on that will install without a firefox restart. it will even get you a working add-on that will update without a firefox restart... usually. some parts work only if you don't look too closely; localization is one of them. as mentioned in the previous section, you'll need to clear the chrome caches on add-on shutdown, namely for chrome images and properties files. doing this will get an update's new properties file to load, however sometimes this will instead produce an error on the next property access. it just doesn't seem that it can reliably clear the cache correctly, for whatever reason. string changes seem to be fine, however the addition or removal of strings can so...
...And 4 more matches
Index - Archive of obsolete content
parts of your add-on in general, into child processes. 104 stylesheet/style modify styles using stylesheet files or css rules. 105 stylesheet/utils helper functions for working with stylesheets. 106 system/child_process an implementation of the node.js child_process api. 107 system/environment access, set and clear environment variables. 108 system/events api for working with the application observer service. 109 system/runtime access to information about firefox's runtime environment. 110 system/unload register callbacks that are called when a module is unloaded. 111 system/xul-app information about the application on w...
...in the past, this had to be simulated by treating the raw data as a string and using the charcodeat() method to read the bytes from the data buffer. 213 tabbox no summary! 214 toolbar add-ons, code snippets, extensions, toolbars ...
... add-ons, best practices, extensions, guide, security this document is intended as a guide for developers to promote best practices in securing your extension. your goal is to keep your users safe. some items mentioned are strict guidelines, meaning that if you don't follow them then your add-on will not be approved on mozilla add-ons. other items are recommendations. the difference will be clearly flagged. 297 session store api add-ons, extensions, firefox, guide, obsolete session store makes it possible for extensions to easily save and restore data across firefox sessions. there is a simple api that lets extensions access the session store feature. 298 setting up an extension development environment add-ons, extensions, guide this article provi...
...And 4 more matches
JSAPI reference
tinterruptcallback added in spidermonkey 31 js_requestinterruptcallback added in spidermonkey 31 js_checkforinterrupt added in jsapi 45 js_destroycontextmaybegc obsolete since jsapi 14 js_setbranchcallback obsolete since javascript 1.9.1 js_setoperationcallback obsolete since jsapi 30 js_getoperationcallback obsolete since jsapi 30 js_triggeroperationcallback obsolete since jsapi 30 js_clearoperationcallback obsolete since javascript 1.9.1 js_getoperationlimit obsolete since javascript 1.9.1 js_setoperationlimit obsolete since javascript 1.9.1 js_max_operation_limit obsolete since javascript 1.9.1 js_operation_weight_base obsolete since javascript 1.9.1 js_setthreadstacklimit obsolete since jsapi 13 js_setscriptstackquota obsolete since javascript 1.8.6 js_setoptions obsole...
...porter js_seterrorreporterobsolete since jsapi 52 js_errorfromexception js_geterrorprototype jsreport_is_exception jsreport_is_strict jsreport_is_warning jsreport_is_strict_mode_error the following functions allow c/c++ functions to throw and catch javascript exceptions: js::createerror added in spidermonkey 38 js_isexceptionpending js_getpendingexception js_setpendingexception js_clearpendingexception js_throwstopiteration added in spidermonkey 1.8 js_isstopiteration added in spidermonkey 31 typedef jsexceptionstate js_saveexceptionstate js_restoreexceptionstate js_dropexceptionstate these functions translate errors into exceptions and vice versa: js_reportpendingexception js_errorfromexception js_throwreportederror obsolete since jsapi 29 values and types ...
... 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 j...
...And 4 more matches
JSDBGAPI
the jsdbg api is obsolete and has been removed in spidermonkey 35. see bug 1069694. ...
... the jsdbg api is obsolete and has been removed in spidermonkey 35. see bug 1069694. ...
... the jsdbg api is obsolete and has been removed in spidermonkey 35. see bug 1069694. ...
...And 4 more matches
Basic animations - Web APIs
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 using the clearrect() 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 i...
... sun.src = 'https://mdn.mozillademos.org/files/1456/canvas_sun.png'; moon.src = 'https://mdn.mozillademos.org/files/1443/canvas_moon.png'; earth.src = 'https://mdn.mozillademos.org/files/1429/canvas_earth.png'; window.requestanimationframe(draw); } function draw() { var ctx = document.getelementbyid('canvas').getcontext('2d'); ctx.globalcompositeoperation = 'destination-over'; ctx.clearrect(0, 0, 300, 300); // clear canvas ctx.fillstyle = 'rgba(0, 0, 0, 0.4)'; ctx.strokestyle = 'rgba(0, 153, 255, 0.4)'; ctx.save(); ctx.translate(150, 150); // earth var time = new date(); ctx.rotate(((2 * math.pi) / 60) * time.getseconds() + ((2 * math.pi) / 60000) * time.getmilliseconds()); ctx.translate(105, 0); ctx.fillrect(0, -12, 40, 24); // shadow ctx.drawimage(earth, ...
... ctx.stroke(); ctx.drawimage(sun, 0, 0, 300, 300); window.requestanimationframe(draw); } init(); <canvas id="canvas" width="300" height="300"></canvas> screenshotlive sample an animated clock this example draws an animated clock, showing your current time. ...
...And 4 more matches
XUL user interfaces - Archive of obsolete content
copy and paste the content from here, making sure that you scroll to get all of it: /*** xul de...
...copy and paste the content from here, making sure that you scroll to get all of it: /*** xul demonstration **...
...copy and paste the content from here, making sure that you scroll to get all of it: /*** xul demonstration ***/ window { -moz-box-align: start; b...
...And 3 more matches
Move the ball - Game development
« previousnext » this is the 2nd step out of 10 of the gamedev canvas tutorial. you can find the source code as it should look after completing this lesson at gamedev-canvas-workshop/lesson2.html. you already know how to draw a ball from working through the previous article, so now let's make it move. technically, we will be painting the ball on the screen, clearing it and then painting it again in a slightly different position every frame to make the impression of movement — just like how movement works with the movies. defining a drawing loop to keep constantly updating the canvas drawing on each frame, we need to define a drawing function that will run over and over again, with a different set of variable values each time to change sprite positions, etc. you can run a fun...
...tion on every update. 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 who...
... 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 this rectangle will be cleared of any content previously painted there. ...
...And 3 more matches
Drawing graphics - Learn web development
raw(); balls[i].update(); balls[i].collisiondetect(); } requestanimationframe(loop); } loop(); we run the loop() function once at the bottom of the code to start the cycle, drawing the first animation frame; the loop() function then takes charge of calling requestanimationframe(loop) to run the next frame of the animation, again and again. note that on each frame we are completely clearing the canvas and redrawing everything. for every ball present we draw it, update its position, and check to see if it is colliding with any other balls. once you've drawn a graphic to a canvas, there's no way to manipulate that graphic individually like you can with dom elements. you can't move each ball around on the canvas, because once it's drawn, it's part of the canvas, and is not an indivi...
...ything, or by having code that knows exactly what parts need to be erased and only erases and redraws the minimum area of the canvas necessary. optimizing animation of graphics is an entire specialty of programming, with lots of clever techniques available. those are beyond what we need for our example, though! in general, the process of doing a canvas animation involves the following steps: clear the canvas contents (e.g. with fillrect() or clearrect()). save state (if necessary) using save() — this is needed when you want to save settings you've updated on the canvas before continuing, which is useful for more advanced applications. draw the graphics you are animating. restore the settings you saved in step 2, using restore() call requestanimationframe() to schedule drawing of the ...
...fox logo. the x coordinate of the slice will have to be a multiple of 102, and the y coordinate will always be 0. the slice size will always be 102 by 148 pixels. now let's insert an empty draw() function at the bottom of the code, ready for filling up with some code: function draw() { }; the rest of the code in this section goes inside draw(). first, add the following line, which clears the canvas to prepare for drawing each frame. notice that we have to specify the top-left corner of the rectangle as -(width/2), -(height/2) because we specified the origin position as width/2, height/2 earlier on. ctx.fillrect(-(width/2), -(height/2), width, height); next, we'll draw our image using drawimage — the 9-parameter version. add the following: ctx.drawimage(image, (spri...
...And 3 more matches
Gecko info for Windows accessibility vendors
ecko also helps determine when to load a new window by firing two event_state_change's on the root role_document accessible -- the first state change indicates the document pane is now busy loading. the second state change indicates the document pane has finished. when handling the event, use get_accstate() to check the state_busy flag. when the document has finished loading the busy flag will be cleared. msaa support: iaccessible methods to use msaa with gecko, you'll need the tools and docs that come with the active accessibility 2.0 sdk tools. the method accessibleobjectfromwindow() will get you the root iaccessible corresponding to the top level window. hold on to this root iaccessible, and use it to walk through the entire tree of iaccessible's. iaccessible methods that we support: ...
...ut of 5. for outline item, more information is provided, in a format that reads "l#, n of m with c" where # represents the level that the outline item is at, and c represents the number of children. the n of m position relates to the position within the current outline level. finally, true descriptions are now exposed with the text "description: " prepending the description. this makes it clear that the description is truly intended to be read. neither "description:" or "of" in the above strings is ever localized, so they should be parsed out. dhtml accessibility is supported this means that you may encounter roles that are not typically in html content. be prepared for new combinations of roles and states in content, such as role_slider, role_progressbar and state_required.
...t_state_change occurs on the root role_document object for a window. the state_busy flag is now set for the root pane object. once the new page is ready to be displayed and traversed via its iaccessible tree, the old content window is destroyed, and a new window is created. next, another event_state_change is fired for the new root role_document object for the window, with its state_busy flag cleared. msaa role support role supported? unique features role_titlebar supported automatically by ms windows role_menubar xul: <menubar> dhtml: role="wairole:menubar" fires event_menustart and event_menuend role_scrollbar not supported n/a role...
...And 3 more matches
imgIContainer
gecko 2.0 void appendpalettedframe(in print32 ax, in print32 ay, in print32 awidth, in print32 aheight, in gfximageformat aformat, in pruint8 apalettedepth, [array, size_is(imagelength)] out pruint8 imagedata, out unsigned long imagelength, [array, size_is(palettelength)] out pruint32 palettedata, out unsigned long palettelength); native code only! obsolete since gecko 2.0 void clear(); obsolete since gecko 1.9.2 gfximagesurface copycurrentframe(); native code only! obsolete since gecko 2.0 gfximagesurface copyframe(in pruint32 awhichframe, in pruint32 aflags); native code only! void decodingcomplete(); obsolete since gecko 2.0 void draw(in gfxcontext acontext, in gfxgraphicsfilter afilter, [const] in gfxmatrix auserspacetoimagespace, [co...
...me. frame_max_value should be set to the value of the maximum constant above, as 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 to...
... obsolete since gecko 2.0 kdisposerestoreprevious 3 restore the previous(composited) frame. ...
...And 3 more matches
nsIDOMMozNetworkStatsManager
read only. maxstorageage long long time in mil...
...read only. maxstorageage long long time in milliseconds recorded by the api until present time. all samples ...
...eshold, and data. exceptions thrown invalidnetwork the network must be in the return of getavailablenetworks. removealarms() remove all network alarms. if an alarmid is provided, then only that alarm is removed. nsidomdomrequest removealarms([optional] in long alarmid); parameters alarmid id of an alarm, like the one returned by addalarm. return value an nsidomdomrequest object. clearstats() remove all stats related with the provided network from db. nsidomdomrequest clearstats(in nsisupports network); parameters network the origin of the data. it can specify wifi, mobile, or null. if null, data measurement from both origins are merged. to know in advance which kind of origin is available, the moznetworkstatsmanager.getavailablenetworks method returns an array of inter...
...And 3 more matches
Key Values - Web APIs
eft", "arrowright", "arrowup", and "arrowdown". editing keys keyboardevent.key value description virtual keycode windows mac linux android "backspace" the backspace key. this key is labeled delete on mac keyboards. vk_back (0x08) kvk_delete (0x33) gdk_key_backspace (0xff08) qt::key_backspace (0x01000003) keycode_del (67) "clear" the clear key. removes the currently selected input. vk_clear (0x0c) vk_oem_clear (0xfe) kvk_ansi_keypadclear (0x47) gdk_key_clear (0xff0b) qt::key_clear (0x0100000b) keycode_clear (28) "copy" the copy key (on certain extended keyboards). appcommand_copy gdk_key_copy (0x1008ff57) qt::key_copy (0x010000cf) "crsel" [3] the cursor sel...
...mer gdk_key_brightnessadjust (0x1008ff3b) "displayswap" cycles among video sources. vk_display_swap "dvr" switches the input source to the digital video recorder (dvr). keycode_dvr (173) "exit" the exit button, which exits the curreent application or menu. ...
...gdk_key_brightnessadjust (0x1008ff3b) "displayswap" cycles among video sources. vk_display_swap "dvr" switches the input source to the digital video recorder (dvr). keycode_dvr (173) "exit" the exit button, which exits the curreent application or menu. ...
...And 3 more matches
Pinch zoom gestures - Web APIs
or zoom in), the element's background color is changed to pink, and if the distance between the pointers is decreasing (a pinch in or zoom out), the background color is changed to lightblue. in a more sophisticated application, pinch in or pinch out determination could be used to apply application-specific semantics. when this event is processed, the target's border is set to dashed to provide a clear visual indication the element has received a move event. function pointermove_handler(ev) { // this function implements a 2-pointer horizontal pinch/zoom gesture. // // if the distance between the two pointers has increased (zoom in), // the target element's background is changed to "pink" and if the // distance is decreasing (zoom out), the color is changed to "lightblue". // // this fun...
... to prevent the browser's default touch behavior from overriding this application's pointer handling, the touch-action property is applied to the <body> element. <body onload="init();" style="touch-action:none"> <div id="target">touch and hold with 2 pointers, then pinch in or out.<br/> the background color will change to pink if the pinch is opening (zoom in) or changes to lig...
... cache management this function helps manage the global event caches evcache. function remove_event(ev) { // remove this event from the target's cache for (var i = 0; i < evcache.length; i++...
...And 3 more matches
Using the User Timing API - Web APIs
(var i=0; i < entries.length; i++) { if (i == 0) log("= getentriesbyname('mark-1', 'mark')", 0); log("... " + entries[i].name, 0); } entries = performance.getentriesbyname("mark-2","mark"); for (var i=0; i < entries.length; i++) { if (i == 0) log("= getentriesbyname('mark-2', 'mark')", 0); log("... ...
...rformance.clearmarks() method is used to remove one or more marks from the browser's performance timeline. if a specific mark name is given to this method, only the mark(s) with that name will be removed. however, if no argument is given, then all performance entries of type "mark" will be removed from the performance timeline. the following example demostrates both uses of this method. function clear_marks(obj) { if (performance.clearmarks === undefined) { log("clear marks: performance.clearmarks not supported", 0); return; } log("clear marks", 0); if (typeof obj == "string") { log("... cleared '" + obj + "' mark(s)", 0); performance.clearmarks(obj); } else { // no argument specified so clear all marks log("... ...
...rates both uses of this method. function clear_marks(obj) { if (performance.clearmarks === undefined) { log("clear marks: performance.clearmarks not supported", 0); return; } log("clear marks", 0); if (typeof obj == "string") { log("... cleared '" + obj + "' mark(s)", 0); performance.clearmarks(obj); } else { // no argument specified so clear all marks log("... cleared all marks", 0); performance.clearmarks(); } } performance measures a measure performance entry type is named by the application and its timestamp is placed between two named marks thus a measure is effectively a midpoint between two marks in the browser's performance timeline. creating a performance measure a measure is created by calling performance.measure(measurename, startmarknam...
...And 3 more matches
WindowOrWorkerGlobalScope.setTimeout() - Web APIs
nction. note: passing additional parameters to the function in the first syntax does not work in internet explorer 9 and below. if you want to enable this functionality on that browser, you must use a polyfill (see the polyfill section). return value the returned timeoutid is a positive integer value which identifies the timer created by the call to settimeout(); this value can be passed to cleartimeout() to cancel the timeout. it may be helpful to be aware that settimeout() and setinterval() share the same pool of ids, and that cleartimeout() and clearinterval() can technically be used interchangeably. for clarity, however, you should try to always match them to avoid confusion when maintaining your code. it is guaranteed that a timeout id will never be reused by a subsequent call to s...
... should try to always match them to avoid confusion when maintaining your code. it is guaranteed that a timeout id will never be reused by a subsequent call to settimeout() or setinterval() on the same object (a window or a worker). however, different objects use separate pools of ids. ...
...call to settimeout() or setinterval() on the same object (a window or a worker). however, different objects use separate pools of ids. example the following example sets up two simple buttons in a web page and hooks them to the settimeout() and cleartimeout() routines. pressing the first button will set a timeout which calls an alert dialog after two seconds and stores the timeout id for use by cleartimeout(). you may optionally cancel this timeout by pressing on the second button. ...
...And 3 more matches
Cognitive accessibility - Accessibility
wcag guidelines wcag, web content accessibility guidelines, includes several guidelines to improve cognitive accessibility. these guidelines are published by the web accessibility initiative (wai) of the world wide web consortium (w3c), the main international standards organization for the internet. this group is also responsible for the accessible ric...
... is navigable and content is findable: include a <title> make sure to include a <title> for the document, as titles provide a quick and easy to reference description of the screen's main point. people with cognitive disabilities, limited short-term memory, and reading disabilities all benefit from being able to identify the purpose of content this way. heading and labels include clear and descriptive headings so users can easily find information and understand relationships between different content sections. descriptive labels help users identify specific components within the content. people who read slowly and people with limited short-term memory benefit when section titles make it possible to predict what each section contains. section headings headings help defi...
...match the visual order when navigating with a keyboard, users can become disoriented. focused elements should be visibly focused when a user navigates using a keyboard, the ui should make it obvious which element currently has focus. don't alter or remove the browser's default :focus styling, unless you're making focus even more obvious. link text conveys meaning the link's text should clearly and concisely communicate what the user should expect to be navigated to next if they choose to activate it. poorly phrased link text may confuse users as to its purpose or destination. some forms of assistive technology allow users to navigate by lists of all the links present on the page. links will be removed from the context of their surrounding non-link content, making the need for unders...
...And 3 more matches
Logical properties for floating and positioning - CSS: Cascading Style Sheets
the logical properties and values specification contains logical mappings for the physical values of float and clear, and also for the positioning properties used with positioned layout. this guide takes a look at how to use these. mapped properties and values the table below details the properties and values discussed in this guide along with their physical mappings. they assume a horizontal writing-mode, with a left-to-right direction. ...
... at how to use these. mapped properties and values the table below details the properties and values discussed in this guide along with their physical mappings. they assume a horizontal writing-mode, with a left-to-right direction. ...
...mapped properties and values the table below details the properties and values discussed in this guide along with their physical mappings. they assume a horizontal writing-mode, with a left-to-right direction. ...
...And 3 more matches
timers - Archive of obsolete content
ssed straight through to the callback. parameters callback : function function to be called. ms : integer interval in milliseconds after which the function will be called. returns integer : an id that can later be used to undo this scheduling, if callback hasn't yet been called. ...
...do this scheduling, if callback hasn't yet been called. example var { settimeout } = require("sdk/timers"); settimeout(function() { // do something in 0 ms }, 0) cleartimeout(id) given an id returned from settimeout(), prevents the callback with the id from being called (if it hasn't yet been called). parameters id : integer an id returned from settimeout(). example var { settimeout, cleartimeout } = require("sdk/timers"); var id = settimeout(function() { // do something in 1 sec }, 1000); // to stop/cancel this timeout cleartimeout(id); setinterval(callback, ms) schedules callback to be called repeatedly every ms milliseconds. any additional arguments are passed straight through to the callback. parameters callback : function function to be called. ms : integer interva...
...additional arguments are passed straight through to the callback. parameters callback : function function to be called. ms : integer interval in milliseconds at which the function will be called. returns integer : an id that can later be used to unschedule the callback. ...
...And 2 more matches
JavaScript Daemons Management - Archive of obsolete content
ation. here are some code snippets that simplify and abstract the management of daemons. the following daemons management framework is the major version of setinterval – a little framework. introduction sometimes a page uses dozens and dozens of animations. in such a condition it is difficult and unnatural to keep track of all events started and then to stop them when appropriate through the cleartimeout() function. a possible approach to solve this problem is to nest all the information needed by each animation to start, stop, etc. in different objects (daemons) and then to create a constructor for such a class of objects (daemon) in order to standardize and simplify the instantiation of them. note: a minimalistic version of it (minidaemon) is published here. this more complex version of...
...you could remove this method, but your daemon will be virtually unusable. * all other optional instances methods...
...n instances methods */ daemon.prototype.isatend = function () { return this.backw ? isfinite(this.length) && this.index < 1 : this.index + 1 > this.length; }; daemon.prototype.synchronize = function () { if (this.paused) { return; } clearinterval(this.session); this.session = setinterval(daemon.forcecall, this.rate, this); }; daemon.prototype.pause = function () { clearinterval(this.session); this.paused = true; }; /* system not required daemon instances methods */ /** * basic user interface. you could remove this method, but your daemon will be virtually unusable. * all other optional instances methods depend on this one or on the previous ones. **/ daemon.prototype.start = function (breverse) { var bbackw = boolean(breverse); if (th...
...And 2 more matches
JavaScript Client API - Archive of obsolete content
in services/sync/modules/record.js. there's a base record object, which defines the basic record api. but, you want to use a derived class, cryptowrapper, which seamlessly encrypts and decrypts records on the client. this makes your synchronized data more secure and unreadable by the server operators. all you have to do is write an object that extends cryptowrapper and maintains a property called cleartext. cleartext must be a json-able object. put into it all values that you want to have encrypted, stored on the server, decrypted, and synced up. you may find it useful to write getters and setters for various properties of your record implementation. the skeleton of a sample record implementation: function foorecord(collection, id) { cryptowrapper.call(this, collection, id); } foorecor...
...pted, and synced up. you may find it useful to write getters and setters for various properties of your record implementation. ...
...ful to write getters and setters for various properties of your record implementation. ...
...And 2 more matches
jspage - Archive of obsolete content
h.alias("foreach","each");array.implement({foreach:function(c,d){for(var b=0,a=this.length;b<a;b++){c.call(d,this[b],b,this);}}});array.alias("foreach","each"); function $a(b){if(b.item){var a=b.length,c=new array(a);while(a--){c[a]=b[a];}return c;}return array.prototype.slice.call(b);}function $arguments(a){return function(){return arguments[a]; };}function $chk(a){return !!(a||a===0);}function $clear(a){cleartimeout(a);clearinterval(a);return null;}function $defined(a){return(a!=undefined);}function $each(c,b,d){var a=$type(c); ((a=="arguments"||a=="collection"||a=="array")?array:hash).each(c,b,d);}function $empty(){}function $extend(c,a){for(var b in (a||{})){c[b]=a[b];}return c; }function $h(a){return new hash(a);}function $lambda(a){return($type(a)=="function")?a:function(){return a;};}fun...
...as no parent.'); }return c.apply(this,arguments);}.protect());},implements:function(a){$splat(a).each(function(b){if(b instanceof function){b=class.instantiate(b);}this.implement(b); },this);}};var chain=new class({$chain:[],chain:function(){this.$chain.extend(array.flatten(arguments));return this;},callchain:function(){return(this.$chain.length)?this.$chain.shift().apply(this,arguments):false; },clearchain:function(){this.$chain.empty();return this;}});var events=new class({$events:{},addevent:function(c,b,a){c=events.removeon(c);if(b!=$empty){this.$events[c]=this.$events[c]||[]; this.$events[c].include(b);if(a){b.internal=true;}}return this;},addevents:function(a){for(var b in a){this.addevent(b,a[b]);}return this;},fireevent:function(c,b,a){c=events.removeon(c); if(!this.$events||!this.$even...
...function(e){var f=this.getelementsbytagname(e.trim());(b)?c.extend(f):c=f; },this);return new elements(c,{ddup:b,cash:!d});}});(function(){var h={},f={};var i={input:"checked",option:"selected",textarea:(browser.engine.webkit&&browser.engine.version<420)?"innerhtml":"value"}; var c=function(l){return(f[l]||(f[l]={}));};var g=function(n,l){if(!n){return;}var m=n.uid;if(browser.engine.trident){if(n.clearattributes){var q=l&&n.clonenode(false); n.clearattributes();if(q){n.mergeattributes(q);}}else{if(n.removeevents){n.removeevents();}}if((/object/i).test(n.tagname)){for(var o in n){if(typeof n[o]=="function"){n[o]=$empty; }}element.dispose(n);}}if(!m){return;}h[m]=f[m]=null;};var d=function(){hash.each(h,g);if(browser.engine.trident){$a(document.getelementsbytagname("object")).each(g); }if(window.
...And 2 more matches
Browser Feature Detection - Archive of obsolete content
ly out of date, it's been archived. you should not rely on any information here. browser sniffing via api name detection the following tables list the api names defined for specific w3c dom apis and lists the percentage of names that your browser actually defines followed by a list of each of the api names tested along with an indication of whether the name was defined for your browser. it is clear from these test results that netscape 7.0x and mozilla firefox have the greatest dom support although internet explorer, safari, and opera have sufficient dom css 1 and dom level 1 & 2 document property and method support to enable cross browser web development. test summary standard netscape 7.0x firefox 1.5 safari 2 opera 7 / 8.5-9.0 internet explorer 6 / 7 ...
...true true borderright true true true borderbottom true true true borderleft true true true bordertopwidth true true true borderrightwidth true true true borderbottomwidth true true true borderleftwidth true true true borderwidth true true true clear true true true color true true true display true true true cssfloat true false true font true true true fontfamily true true true fontsize true true true fontstyle true true true fontvariant true true true fontweight true true t...
... true borderbottomcolor true true true borderleftcolor true true true bordertopstyle true true true borderrightstyle true true true borderbottomstyle true true true borderleftstyle true true true 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 ...
...And 2 more matches
Index - Learn web development
article, beginner, css, css layouts, codingscripting, flexible boxes, guide, layout, layouts, learn, flexbox 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. 143 floats article, beginner, css, clearing, codingscripting, floats, guide, layout, columns, multi-column 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. 144 grids article, beginner, css, css grids, codingscripting, grids, guide, layout, ...
...column-count, column-width, column-gap, column-span and column-rule properties and values covered in our lesson on multiple-column layout. you will be working through three small tasks which use different elements of the material you have just covered. 158 test your skills: floats beginner, css, example, guide the aim of this task is to get you working with the css float and clear properties covered in our lesson on floats. you will be working through three small tasks which use different elements of the material you have just covered. 159 test your skills: position css, example, guide the aim of this task is to get you working with the css position property and values covered in our lesson on position. you will be working through two small tasks which...
...nality. our app can display, add, and delete todos, toggle their completed status, show how many of them are completed and apply filters. 279 ember interactivity: footer functionality, conditional rendering beginner, ember, frameworks, javascript, learn, client-side, conditional rendering that's enough for now. at this point, not only can we mark todos as complete, but we can clear them as well. now the only thing left to wire up the footer are the three filtering links: "all", "active", and "completed". we'll do that in the next article, using routing. 280 ember app structure and componentization beginner, components, ember, frameworks, javascript, learn, client-side great! everything looks as it should. we have successfully refactored our html into co...
...And 2 more matches
Timer.jsm
the timer.jsm javascript code module contains pure-javascript implementations of settimeout, cleartimeout, setinterval, and clearinterval that are compatible with the dom window functions, but that can be used by code that does not have access to a dom window (for example, javascript code modules or content frame scripts). ...
...-javascript implementations of settimeout, cleartimeout, setinterval, and clearinterval that are compatible with the dom window functions, but that can be used by code that does not have access to a dom window (for example, javascript code modules or content frame scripts). ...
...ns, but that can be used by code that does not have access to a dom window (for example, javascript code modules or content frame scripts). ...
...And 2 more matches
nsIMsgFolder
n nsimsgwindow msgwindow); void renamesubfolders( in nsimsgwindow msgwindow, in nsimsgfolder oldfolder); astring generateuniquesubfoldername(in astring prefix,in nsimsgfolder otherfolder); void updatesummarytotals(in boolean force); void summarychanged(); long getnumunread(in boolean deep); long gettotalmessages(in boolean deep); void clearnewmessages(); void clearrequirescleanup(); void setflag(in unsigned long flag); void clearflag(in unsigned long flag); boolean getflag(in unsigned long flag); void toggleflag(in unsigned long flag); void onflagchange(in unsigned long flag); void setprefflag(); nsimsgfolder getfolderswithflag(in unsigned long flags, in unsigne...
... otherfolder); updatesummarytotals() void updatesummarytotals(in boolean force); summarychanged() void summarychanged(); getnumunread() get the total number of unread messages in this folder, or in all subfolders. long getnumunread(in boolean deep); gettotalmessages() get the total number of messages in this folder, or in all subfolders. ...
...atesummarytotals() void updatesummarytotals(in boolean force); summarychanged() void summarychanged(); getnumunread() get the total number of unread messages in this folder, or in all subfolders. long getnumunread(in boolean deep); gettotalmessages() get the total number of messages in this folder, or in all subfolders. ...
...And 2 more matches
Browser Console - Firefox Developer Tools
the window is occupied by a pane that display messages. at the top, a toolbar enables you to filter the messages that appear. at the bottom, a command line interpreter enables you to evaluate javascript expressions. beginning with firefox 68, the browser console allows you to show or hide messages from the content process (i.e. the messages from scripts in all the opened pages) by setting or clearing the checkbox labeled show content messages. the following image shows the browser console focused on the same page as above after clicking on the show content messages checkbox. browser console logging the browser console logs the same sorts of messages as the web console: http requests warnings and errors (including javascript, css, security warnings and errors, and messages explicitl...
...s/console.jsm"); console.log("hello from firefox code"); //output messages to the console learn more: console api reference console.jsm source code in the mozilla dxr hudservice there is also the hudservice which allows access to the browse console. the module is available at mozilla dxr. we see we can not only access the browser console but also web console. here is an example on how to clear the contents of the browser console: components.utils.import("resource://devtools/shared/loader.jsm"); var hudservice = devtools.require("devtools/client/webconsole/hudservice"); var hud = hudservice.getbrowserconsole(); hud.jsterm.clearoutput(true); if you would like to access the content document of the browser console this can be done with the hudservice. this example here makes it so that ...
...ser console: components.utils.import("resource://devtools/shared/loader.jsm"); var hudservice = devtools.require("devtools/client/webconsole/hudservice"); var hud = hudservice.getbrowserconsole(); hud.jsterm.clearoutput(true); if you would like to access the content document of the browser console this can be done with the hudservice. ...
...And 2 more matches
Dragging and Dropping Multiple Items - Web APIs
caution: all of the methods and properties with a moz prefix (such as mozsetdataat() are gecko specific interfaces. these interfaces will only work with gecko based browsers. mozilla supports the ability to drag multiple items using some additional non-standard methods. these are methods that mirror the types property as well as the getdata(), setdata() and cleardata() methods, however, they take an additional argument that specifies the index of the item to retrieve, modify or remove. the drag processing described in this document use the datatransfer interface. this processing does not use the datatransferitem interface nor the datatransferitemlist interface. setting and getting with indices the mozsetdataat() method allows you to add multiple items during a dragstart event. this fun...
..."text/plain", "second data to drag", 1); this example adds two items to be dragged. the last argument specifies the index of the item to add. you should add them in order starting with 0 as you cannot add items at positions farther than the last item, however you can replace existing items by using indices you have already added. using 0 as the index is equivalent to calling setdata(). you can clear an item using the mozcleardataat() method. event.datatransfer.mozcleardataat("text/plain", 1); caution: removing the last format for a particular index will remove that item entirely, shifting the remaining items down, so the later items will have different indices. for example: var dt = event.datatransfer; dt.mozsetdataat("text/uri-list", "url1", 0); dt.mozsetdataat("text/plain", "url1", ...
... common case...
...And 2 more matches
Using IndexedDB - Web APIs
ent number of a key generator is always set to 1 when the object store for that key generator is first created. basically the newly auto-generated key is increased by 1 based on the previous key. the current number for a key generator never decreases, other than as a result of database operations being reverted, for example, the database transaction is aborted. therefore deleting a record or even clearing all records from an object store never affects the object store's key generator. we can create another object store with the key generator as below: // open the indexeddb. var request = indexeddb.open(dbname, 3); request.onupgradeneeded = function (event) { var db = event.target.result; // create another object store called "names" with the autoincrement flag set as true. ...
...action to complete, and on older browsers, you don't even get told when they don't complete. there are several implications of this behavior. first, you should take care to always leave your database in a consistent state at the end of every transaction. for example, suppose that you are using indexeddb to store a list of items that you allow the user to edit. you save the list after the edit by clearing the object store and then writing out the new list. if you clear the object store in one transaction and write the new list in another transaction, there is a danger that the browser will close after the clear but before the write, leaving you with an empty database. to avoid this, you should combine the clear and the write into a single transaction. second, you should never tie database tra...
...>(for example 1, 2, 3, etc.)</span> </label> </td> <td> <input type="text" id="key-to-delete" name="key-to-delete" /> </td> </tr> </tbody> </table> <div class="button-pane"> <input type="button" id="delete-button" value="delete publication" /> <input type="button" id="clear-store-button" value="clear the whole store" class="destructive" /> </div> </form> <form id="search-form"> <div class="button-pane"> <input type="button" id="search-list-button" value="list database content" /> </div> </form> <div> <div id="pub-msg"> </div> <div id="pub-viewer"> </div> <ul id="p...
...And 2 more matches
KeyboardEvent.key - Web APIs
Web › API › KeyboardEvent › key
keyboard layout. try experimenting using the following two test cases: press and hold the shift key, then press 2 and release it. next, release the shift key. press and hold the shift key, then press and hold 2. release the shift key. finally, release 2. ...
...xperimenting using the following two test cases: press and hold the shift key, then press 2 and release it. next, release the shift key. press and hold the shift key, then press and hold 2. release the shift key. finally, release 2. ...
...ing the following two test cases: press and hold the shift key, then press 2 and release it. next, release the shift key. press and hold the shift key, then press and hold 2. release the shift key. finally, release 2. ...
...And 2 more matches
Storage API - Web APIs
ach site storage unit is called its box. each site storage unit has exactly one box into which all of its data is placed, and has a box mode that describes the data retention policy for that box. there are two modes: "best-effort" the user agent will try to retain the data contained in the box for as long as it can, but will not warn users if storage space runs low and it becomes necessary to clear the box in order to relieve the storage pressure. "persistent" the user agent will retain the data as long as possible, clearing all "best-effort" boxes before considering clearing a box marked "persistent". if it becomes necessary to consider clearing persistent boxes, the user agent will notify the user and provide a way to clear one or more persistent boxes as needed. to change an origin's...
...it's also possible for the user agent to decide to make the site's storage unit persistent due to usage characteristics or other metrics. ...
...permission, except that the permission state must be the same across the entire origin, and that if the permission state isn't "granted" (meaning that for whatever reason, access to the persistent storage feature was denied), the origin's site storage unit's box mode is always "best-effort". note: see using the permissions api for further details about obtaining and managing permissions. when clearing site storage units, an origin's box is treated as a single entity; if the user agent needs to clear it and the user approves, the entire data store is cleared rather than providing some means of clearing only data from individual apis. if a box is marked as "persistent", the contents won't be cleared by the user agent without either the data's origin itself or the user specifically doing so. ...
...And 2 more matches
WebGLRenderingContext - Web APIs
a single equation. webglrenderingcontext.blendequationseparate() sets the rgb blend equation and alpha blend equation separately. webglrenderingcontext.blendfunc() defines which function is used for blending pixel arithmetic. webglrenderingcontext.blendfuncseparate() defines which function is used for blending pixel arithmetic for rgb and alpha components separately. webglrenderingcontext.clearcolor() specifies the color values used when clearing color buffers. webglrenderingcontext.cleardepth() specifies the depth value used when clearing the depth buffer. webglrenderingcontext.clearstencil() specifies the stencil value used when clearing the stencil buffer. webglrenderingcontext.colormask() sets which color components to enable or to disable when drawing or rendering to a webgl...
...for a uniform variable. webglrenderingcontext.uniformmatrix[234]fv() specifies a matrix value for a uniform variable. webglrenderingcontext.vertexattrib[1234]f[v]() specifies a value for a generic vertex attribute. webglrenderingcontext.vertexattribpointer() specifies the data formats and locations of vertex attributes in a vertex attributes array. drawing buffers webglrenderingcontext.clear() clears specified buffers to preset values. webglrenderingcontext.drawarrays() renders primitives from array data. webglrenderingcontext.drawelements() renders primitives from element array data. webglrenderingcontext.finish() blocks execution until all previously called commands are finished. webglrenderingcontext.flush() empties different buffer commands, causing all commands to be ex...
..., send data to the webgl, and execute draw commands. saving the state of the graphics machine within a single context interface is not unique to webgl. this is also done in other graphics {̣{glossary("api")}}, such as the canvas 2d rendering context. however, the properties and variables you can tweak are different for each api. effect of canvas size on rendering with webgl with scissor() and clear() we can demonstrate how the webgl drawing buffer is affected by the size of the canvas. the size of the first canvas is set to the styled element size, determined by css. this is done by assigning the width and height properties of the canvas to the values of the clientwidth and clientheight properties, respectively. in contrast, no such assignment is done for the second canvas. the internal w...
...And 2 more matches
Raining rectangles - Web APIs
« previousnext » a simple webgl game that demonstrates clearing with solid colors, scissoring, animation, and user interaction. animation and user interaction with scissoring this is a simple game. the objective: try to catch as many of the raining rectangles as you can by clicking on them. in this example, we use an object-oriented approach for the displayed rectangles, which helps to keep the state of the rectangle (its position, color, and so on) organized in one place, and the overall code more compact and reusable. this example combines clearing the drawing buffer with solid colors and scissoring operations. it is a preview of a full graphical application that manipulates various phases of the webgl graphics pipeline and state machine. in addition, the example demonstr...
...so we reschedule // the timeout to call drawanimation again in 17ms. // otherwise we won't get any animation. timer = settimeout(drawanimation, 17); ...
...// because we want horizontal size, vertical size and // position to be determined independently. ...
...And 2 more matches
Adding 2D content to a WebGL context - Web APIs
positions for the object. rendering the scene once the shaders are established, the locations are looked up, and the square plane's vertex positions put in a buffer, we can actually render the scene. since we're not animating anything in this example, our drawscene() function is very simple. it uses a few utility routines we'll cover shortly. ...
... the scene once the shaders are established, the locations are looked up, and the square plane's vertex positions put in a buffer, we can actually render the scene. since we're not animating anything in this example, our drawscene() function is very simple. it uses a few utility routines we'll cover shortly. ...
...stablished, the locations are looked up, and the square plane's vertex positions put in a buffer, we can actually render the scene. since we're not animating anything in this example, our drawscene() function is very simple. it uses a few utility routines we'll cover shortly. ...
...And 2 more matches
Rendering and the WebXR frame animation callback - Web APIs
ay, and targeting that is usually a good baseline to follow. 60 fps is already beyond the point at which most people can easily detect that the animation isn't simply a series of still images going by really fast. in other words, when in doubt, you can assume that the display is refreshing at 60 hz. as long as your code is written properly, everything will be fine. renderer performance concerns clearly, you have very little time to render your scene each frame. not only that, but if your renderer itself runs longer than that amount of time, you can cause not just the frame to get dropped, but that time to be wasted entirely, blocking other code from getting to run at all for that frame. not only that, but if your rendering crosses the vertical refresh boundary, you can wind up with a tearing...
...tionframe(mydrawframe); // get an xrviewerpose representing the position and // orientation of the viewer. if successful, render the // frame. viewerpose = frame.getviewerpose(viewerrefspace); if (viewerpose) { let gllayer = session.renderstate.baselayer; gl.bindframebuffer(gl.framebuffer, gllayer.framebuffer); // start by erasing the color and depth framebuffers. gl.clearcolor(0, 0, 0, 1.0); gl.cleardepth(1.0); gl.clear(gl.color_buffer_bit | gl.depth_buffer_bit); // compute the time elapsed since the last frame was rendered. // use this value to ensure your animation runs at the exact // rate you intend. const deltatime = currentframetime - lastframetime; lastframetime = time; // now call the scene rendering code once for each of...
...erty, then getting the framebuffer from that xrwebgllayer object. we then call gl.bindframebuffer() to bind that framebuffer as the target for all upcoming drawing commands. the next step is to erase the framebuffer. ...
...And 2 more matches
Visualizations with Web Audio API - Web APIs
some specific examples. ...
... 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(dataarray); next, fill the canvas with a solid colour to start canvasc...
...function to start off the whole process: draw(); this gives us a nice 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. ...
...And 2 more matches
-webkit-mask-composite - CSS: Cascading Style Sheets
the -webkit-mask-composite property specifies the manner in which multiple mask images applied to the same element are composited with one another. mask images are composited in the opposite order that they are declared with the -webkit-mask-image property. ...
...-composite: destination-in; -webkit-mask-composite: destination-out; -webkit-mask-composite: destination-atop; -webkit-mask-composite: xor; /* global values */ -webkit-mask-composite: inherit; -webkit-mask-composite: initial; -webkit-mask-composite: unset; there is a standardized mask-composite property covering parts of this non-standard property using different keywords. syntax values clear overlapping pixels in the source mask image and the destination mask image are cleared. copy the source mask image replaces the destination mask image. source-over the source mask image is rendered over the destination mask image. source-in overlapping pixels in the source mask image and the destination mask image are replaced by the pixels of the source mask image; all other pixels are cl...
...e source mask image replaces the destination mask image. source-over the source mask image is rendered over the destination mask image. source-in overlapping pixels in the source mask image and the destination mask image are replaced by the pixels of the source mask image; all other pixels are cleared. source-out overlapping pixels in the source mask image and the destination mask image are cleared; all remaining pixels of the source mask image are rendered. source-atop the pixels of the destination mask image are rendered. the pixels of the source mask image are rendered only if they overlap a nontransparent portion of the destination mask image. this causes the source mask image to have no effect. destination-over the destination mask image is rendered over the source mask image. d...
...And 2 more matches
Style System Overview - Archive of obsolete content
le: italic; } css style rule representation each declaration block is represented by an nscssdeclaration an cssstyleruleimpl contains each selector associated with that declaration, and the declaration, and is the most important implementation of nsistylerule. the declarations (properties & values) are stored in data structs (nscss*). the data format of the structs and selectors is mostly clear from the code and not worth going into (although the implementation of :not() is confusing). css style rule representation h1, h2 { color: green; text-align: right; text-indent: 0; } cssstyleruleimpl cssstyleruleimpl ↓ ↓ ↓ ↓ h1 nscssdeclaration h2 ↙ ↘ nscsscol...
...is much more accurate. the cssruleprocessor implementation does a slightly modified form of selector matching to implement it (includes matching on the middle of selectors to catch p:hover a). style attribute changes we handle style attribute (“inline style”) changes in a different way from other changes to style rules. as for other style changes, we have to “walk” the rule tree and clear all the style data coming from the old inline style nsistylerule, since there could be an !important rule that overrides it, which would allow dynamic changes to put the style attribute in multiple places in the rule tree. however, we maintain a hashtable just for inline style rules so that we don't have to walk the whole tree to find the nodes. nscssframeconstructor::attributechanged only re-re...
...ll::reconstructstyledata calls framemanager::computestylechangefor (reresolve) and then processes the frame-change list. rebuilds rule tree if stylesheet was removed to avoid dangling pointers (and perhaps aliasing that would cause problems). otherwise we'd have to walk rule tree and compare each rule node to every rule in the sheet (o(rules * rule-nodes)). ...
...rebuilding rule tree, we have to clear cached style contexts from xul menus and trees. style rule changes handling of style rule changes is done in frame constructor (called from style set, called from pres shell, which is a document observer) and in the pres shell. code should be merged. rule change applies the rule-struct hint as if the rule matched the root element. (inefficient) it does clearing of style data (through stylesetimpl::clearstyledata) by walking the rule tree and then the style context tree. (could be handled by simultaneous clearing and difference calculation of data (somewhat tricky)) rule addition and removal just rebuild the entire world. we could at least do what we do for sheet addition/removal, or slightly better, by searching the rule tree (only one rule this tim...
Menu - Archive of obsolete content
Archive › Mozilla › Jetpack › UI › Menu
ibing the context in which the menu was shown. beforeshow may modify the menu, and when the menu is shown, it will reflect the changes. isshowing boolean true if the menu is currently visible and false otherwise. read-only. items array an array of menuitems in the menu. read-only. methods add(items) clear() contexton(node) hide() insertbefore(newitems, target) item(target) popupon(node) remove(target) replace(target, newitems) reset() set(items) show(anchornode) add(items) adds items to the menu. the position at which th...
... replace(target, newitems) reset() set(items) show(anchornode) add(items) adds items to the menu. the position at which the items are added is at jetpack's discretion. this method and set() are the recommended methods of adding items to a menu. parameters items a single menuitem or an array of menuitems. clear() removes all items from the menu, even items not added by the feature. contexton(node) binds the menu to a given node as its context menu. parameters node the menu is attached to this node, which may be either a raw dom node or a dom node wrapped by jquery. hide() hides the menu if it is showing. insertbefore(newitems, target) inserts new items before an existing item. parameter...
...ls. replace(target, newitems) replaces an item with new items. parameters target indicates the existing item to replace. see targets. if no such target exists, the call silently fails. newitems a single menuitem or an array of menuitems. reset() reverts all the changes to the menu that the feature has made. for menus that the feature creates, this is equivalent to clear(). set(items) equivalent to calling reset() and then add(items). this method and add() are the recommended methods of adding items to a menu. parameters items a single menuitem or an array of menuitems. show(anchornode) shows the menu immediately. parameters anchornode the menu will pop up on this node, which may be either a raw dom node or a dom node wrapped by j...
...set jetpack's solution is to expose contextmenuset objects. a contextmenuset represents a set of context menus. jetpack.menu.context.page is the set of context menus that appear on the page: the image menu, link menu, and so on. contextmenuset defines many of the same methods that jetpack.menu does. features can use these methods to modify all the menus in a set at once. they are: add(items) clear() insertbefore(newitems, target) remove(target) replace(target, newitems) reset() set(items) the following jetpack.menu properties can also be defined on a contextmenuset: beforehide beforeshow note that a jetpack.menu object is passed to beforehide and beforeshow, since they are called during a context menu's invocation. they may then modify the menu. individual menus are drawn ...
New Skin Notes - Archive of obsolete content
ntional? --nickolay i didn't ever notice that they were different, honestly. i'll take a look. --dria ok, the difference on the cavendish theme is negligible (to the point where i never noticed). direct external links have icons to differentiate them from internal links, so i think we'll just leave the internal/external links colours the same. ==dria you've got to be kidding me, the colors are clearly different (rgb(0,51,153) vs rgb(51,102,187)). --nickolay 09:19, 25 aug 2005 (pdt) (moving this to a new item) on the contrary, the list of categories current page belongs to, should be near the footer (see mdc:policies_and_guidelines page) (dria: fix catlinks style) the arrows that appear if you select "enhanced recent changes" in your preferences have an ugly border around them. --nicko...
...it box, category list on category pages, and others are always below the end of the sidebar. ...
...skin - that they were out of the screen - is solved by making the sidebar smaller, which is not the right thing to do, imo (see my comment 1).--nickolay 02:11, 25 aug 2005 (pdt) yeah this is actually a problem with mw, rather than the skin -- they use a <br style="clear:both" /> in some pretty annoying places. i'll try to get those fixed today. --dria well, with mediawiki skin, you can have the clear:both's in content area without a problem. i understand it might be hard to fix in the skin, but it is very desirable (because we sometimes use the floats and 'clears' in our pages). --nickolay 04:52, 25 aug 2005 (pdt) the clear/boths aren't in the content, they're embedded style information in the .php files in the /includes directory. it's just sloppy coding. i cannot think of any reason for wr...
...ithout a problem. i understand it might be hard to fix in the skin, but it is very desirable (because we sometimes use the floats and 'clears' in our pages). --nickolay 04:52, 25 aug 2005 (pdt) the clear/boths aren't in the content, they're embedded style information in the .php files in the /includes directory. it's just sloppy coding. i cannot think of any reason for writers or editors to add "clear:both" brs to their document. under what situations does this seem like something that should be embedded directly into the wiki content? --dria when using floated divs - images and such. if you don't use it they overlap with headings, which is something we seldom want. see for example the venkman tutorials (although the clears are down the page) or mdc:frequently asked questions. i'm not saying ...
CSS - Archive of obsolete content
Archive › Web › CSS
this pseudo-element is non-standard, supported only in internet explorer 10, internet explorer 11, and microsoft edge.::-ms-expandthe ::-ms-expand css pseudo-element is a microsoft extension that represents the button of a <select> menu control that opens or c...
...this pseudo-element is non-standard, supported only in internet explorer 10, internet explorer 11, and microsoft edge.::-ms-expandthe ::-ms-expand css pseudo-element is a microsoft extension that represents the button of a <select> menu control that opens or closes the drop-...
...this pseudo-element is non-standard, supported only in internet explorer 10, internet explorer 11, and microsoft edge.::-ms-expandthe ::-ms-expand css pseudo-element is a microsoft extension that represents the button of a <select> menu control that opens or closes the drop-down menu. typically it is a triang...
...soft extension that represents the button that opens the file picker of <input type="file">.::-ms-checkthe ::-ms-check css pseudo-element is a microsoft extension that represents checkboxes and radio button groups created by <input type="checkbox"> and <input type="radio">.::-ms-clearthe ::-ms-clear css pseudo-element creates a clear button at the edge of an <input type="text"> text control that clears the current value. this pseudo-element is non-standard, supported only in internet explorer 10, internet explorer 11, and microsoft edge.::-ms-expandthe ::-ms-expand css pseudo-element is a microsoft extension that represents the button of a <select> menu control that opens or closes the drop-down menu. typically it is a triangle that points downward.::-ms-fillthe ::-ms-fill css pseudo-element i...
Index - MDN Web Docs Glossary: Definitions of Web-related terms
itespace. 74 chrome browser, chrome, glossary, webmechanics in a browser, the chrome is any visible aspect of a browser aside from the webpages themselves (e.g., toolbars, menu bar, tabs). this is not to be confused with the google chrome browser. 75 cipher cryptography, glossary, privacy, security in cryptography, a cipher is an algorithm that can encode cleartext to make it unreadable, and to decode it back. 76 cipher suite cryptography, glossary, security a cipher suite is a combination of a key exchange algorithm, authentication method, bulk encryption cipher, and message authentication code. 77 ciphertext cryptography, glossary, privacy, security in cryptography, a ciphertext is a scrambled message that con...
... a combination of a key exchange algorithm, authentication method, bulk encryption cipher, and message authentication code. 77 ciphertext cryptography, glossary, privacy, security in cryptography, a ciphertext is a scrambled message that conveys information but is not legible unless decrypted with the right cipher and the right secret (usually a key), reproducing the original cleartext. a ciphertext's security, and therefore the secrecy of the contained information, depends on using a secure cipher and keeping the key secret. 78 class codingscripting, glossary in object-oriented programming, a class defines an object's characteristics. class is a template definition of an object's properties and methods, the "blueprint" from which other more specific in...
...he letters, which are typically used for control signaling by the telephone network. 105 data structure codingscripting, data structure, glossary data structure is a particular way of organizing data so that it can be used efficiently. 106 decryption cryptography, glossary, privacy, security in cryptography, decryption is the conversion of ciphertext into cleartext. 107 delta delta, glossary, difference, value the term delta refers to the difference between two values or states. 108 denial of service attack, denial of service, glossary, intro, security dos (denial of service) is a network attack that prevents legitimate use of server resources by flooding the server with requests. 109 descriptor (css)...
... (for example, a class) and then controlling access to that component to make a "blackbox" out of the object. because of this, a user of that class only needs to know its interface (that is, the data and functions exposed outside the class), not the hidden implementation. 130 encryption cryptography, glossary, privacy, security in cryptography, encryption is the conversion of cleartext into a coded text or ciphertext. a ciphertext is intended to be unreadable by unauthorized readers. 131 endianness coding, codingscripting, glossary endian and endianness (or "byte-order") describe how computers organize the bytes that make up numbers. 132 engine codingscripting, glossary, needscontent the javascript engine is an interpreter that pars...
HTML: A good basis for accessibility - Learn web development
reader hasn't got anything to use as signposts, so you can't retrieve a useful table of contents, and the whole page is seen as a single giant block, so it is just read out in one go, all at once. there are other issues too beyond accessibility — it is harder to style the content using css, or manipulate it with javascript, for example, because there are no elements to use as selectors. using clear language the language you use can also affect accessibility. in general, you should use clear language that is not overly complex and doesn't use unnecessary jargon or slang terms. this not only benefits people with cognitive or other disabilities; it benefits readers for whom the text is not written in their first language, younger people ... everyone, in fact! apart from this, you should try t...
...for example: don't use dashes if you can avoid it. instead of writing 5–7, write 5 to 7. expand abbreviations — instead of writing jan, write january. expand acronyms, at least once or twice. instead of writing html in the first instance, write hypertext markup language. ...
...nd bad-links.html. form labels are also important for giving you a clue about what you need to enter into each form input. the following seems like a reasonable enough example: fill in your name: <input type="text" id="name" name="name"> however, this is not so useful for disabled users. ...
...this gives the input a bigger hit area, making it easier to select. ...
HTML: A good basis for accessibility - Learn web development
reader hasn't got anything to use as signposts, so you can't retrieve a useful table of contents, and the whole page is seen as a single giant block, so it is just read out in one go, all at once. there are other issues too beyond accessibility — it is harder to style the content using css, or manipulate it with javascript, for example, because there are no elements to use as selectors. using clear language the language you use can also affect accessibility. in general, you should use clear language that is not overly complex and doesn't use unnecessary jargon or slang terms. this not only benefits people with cognitive or other disabilities; it benefits readers for whom the text is not written in their first language, younger people ... everyone, in fact! apart from this, you should try t...
...for example: don't use dashes if you can avoid it. instead of writing 5–7, write 5 to 7. expand abbreviations — instead of writing jan, write january. expand acronyms, at least once or twice. instead of writing html in the first instance, write hypertext markup language. ...
...nd bad-links.html. form labels are also important for giving you a clue about what you need to enter into each form input. the following seems like a reasonable enough example: fill in your name: <input type="text" id="name" name="name"> however, this is not so useful for disabled users. ...
...this gives the input a bigger hit area, making it easier to select. ...
Working with Svelte stores - Learn web development
on'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 const...
...imeout to remove the alert. we'll also take care of clearing the timeout when the alert component is unmounted to prevent memory leaks. ...
... // hide alert if message is empty visible = false } else { visible = true // show alert if (ms > 0) timeout = settimeout(() => visible = false, ms) // and hide it after ms milliseconds } } $: onmessagechange($alert, ms) // whenever the alert store or the ms props changes run onmessagechange ondestroy(()=> cleartimeout(timeout)) // make sure we clean-up the timeout </script> and update the alert.svelte markup section like so: {#if visible} <div on:click={() => visible = false}> <svg xmlns="http://www.w3.org/2000/svg" viewbox="0 0 20 20"><path d="m12.432 0c1.34 0 2.01.912 2.01 1.957 0 1.305-1.164 2.512-2.679 2.512-1.269 0-2.009-.75-1.974-1.99c9.789 1.436 10.67 0 12.432 0zm8.309 20c-1...
... whether the alert is visible or not. with $: onmessagechange($alert, ms) we tell svelte to run this function whenever the $alert store or the ms prop changes. whenever the $alert store changes, we'll clean up any pending timeout. if $alert is empty, we set visible to false and the alert will be removed from the dom. if it is not empty, we set visible to true and use the settimeout() function to clear the alert after ms milliseconds. finally, with the ondestroy() lifecycle function, we make sure to call the cleartimeout() function. we also added an svg icon above the alert paragraph, to make it look a bit nicer. try it out again, and you should see the changes. making our alert component accessible our alert component is working fine, but it's not very friendly to assistive technologies. t...
What to do and what not to do in Bugzilla
when you resolve a bug, cc yourself so that you are informed when new facts come up. the conditions for not resolving a bug always overrule the conditions for resolving a bug. when in doubt about resolving a bug, leave it alone! resolving bugs as duplicate in general newer bugs should be marked as duplicates of older bugs, except when the newer bug contains more information (bug description clearer, patch already attached, lots of people already cc'ed, etc.). resolving bugs as worksforme you can resolve a bug as worksforme (wfm) if it can't be reproduced on the reported hardware/os. you should not resolve a bug as wfm if: the bug reporter uses a different hardware/operating system (e.g. bug appears on linux and you can't reproduce it on windows). the bug has been reproduced by some...
...g the issue. if there are only a few comments in the bug, it may be reopened only if the original reporter provides more info, or confirms someone else's steps to reproduce. if the bug is long, when enough info is provided a new bug should be filed and the original bug marked as a duplicate of it. resolving bugs as invalid you should resolve a bug as invalid if the issue described in the bug is clearly not a mozilla bug or if the issue is intended behavior. the exceptions are bugs in other software which we have to work around and bugs that involve certain core gecko modules. bugs covered by this exception should not be invalidated by anyone other than the module owner or module peer; for bugs involving modules like layout or content, attach a test case to the bug and then cc one of the owner...
... 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 detection works in bugzilla, you should try not to verify bugs immediately after they're marked fixed; instead, let a little time pass first. this isn't mandatory, but can help prevent accidental fili...
...e come up. note: because of how duplicate detection works in bugzilla, you should try not to verify bugs immediately after they're marked fixed; instead, let a little time pass first. this isn't mandatory, but can help prevent accidental filing of duplicates of a bug that's already been fixed. changing the bug information fields summary you should change the summary if the current one is unclear or does not correctly describe the issue covered by the bug. you should not change the summary in order to morph the bug to describe a different issue. in this case the bug should be resolved and another bug should be opened. os/hardware make sure that the os or hardware fields correctly display the systems that are affected. if a bug is windows-only, change the field to the oldest affected ope...
HTTP Cache
the cache api is completely thread-safe and non-blocking. there is no ipc support. it's only accessible on the default chrome process. ...
...ation caches application cache (appcachestorage): when a consumer has a specific nsiapplicationcache (i.e. ...
...tioncache (i.e. ...
...pool and cacheentry background operations close: file closing level index: index is being rebuild here evict: files overreaching the disk space consumption limit are being evicted here note: special case for eviction - when an eviction is scheduled on the io thread, all operations pending on the open level are first merged to the open_priority level. the eviction preparation operation - i.e. clearing of the internal io state - is then put to the end of the open_priority level. all this happens atomically. this functionality is currently pending in bug 976866. storage and entries scopes a scope key string used to map the storage scope is based on the arguments of nsiloadcontextinfo. the form is following (currently pending in bug 968593): a,b,i1009,p, regular expression: (.([^,]+)?,)...
NSS functions
.2 and later ssl_canbypass mxr 3.11.7 and later ssl_cipherpolicyget mxr 3.2 and later ssl_cipherpolicyset mxr 3.2 and later ssl_cipherprefget mxr 3.2 and later ssl_cipherprefgetdefault mxr 3.2 and later ssl_cipherprefset mxr 3.2 and later ssl_cipherprefsetdefault mxr 3.2 and later ssl_clearsessioncache mxr 3.2 and later ssl_configmpserversidcache mxr 3.2 and later ssl_configsecureserver mxr 3.2 and later ssl_configserversessionidcache mxr 3.2 and later ssl_datapending mxr 3.2 and later ssl_forcehandshake mxr 3.2 and later ssl_forcehandshakewithtimeout mxr 3.11.4 and later ssl_get...
... nss versions cert_addcerttolisttail mxr 3.2 and later cert_addextension mxr 3.5 and later cert_addocspacceptableresponses mxr 3.6 and later cert_addokdomainname mxr 3.4 and later cert_addrdn mxr 3.2.1 and later cert_asciitoname mxr 3.2 and later cert_cachecrl mxr 3.10 and later cert_clearocspcache mxr 3.11.7 and later cert_certchainfromcert mxr 3.2 and later cert_certlistfromcert mxr 3.2 and later cert_certtimesvalid mxr 3.2 and later cert_changecerttrust mxr 3.2 and later cert_checkcertvalidtimes mxr 3.2 and later cert_checknamespace mxr 3.12 and later cert_checkcertusage m...
... port_zfree mxr 3.2 and later rsa_formatblock mxr 3.2 and later sec_asn1decode mxr 3.4 and later sec_asn1decodeinteger mxr 3.2 and later sec_asn1decodeitem mxr 3.2 and later sec_asn1decoderabort mxr 3.9 and later sec_asn1decoderclearfilterproc mxr 3.2 and later sec_asn1decoderclearnotifyproc mxr 3.2 and later sec_asn1decoderfinish mxr 3.2 and later sec_asn1decodersetfilterproc mxr 3.2 and later sec_asn1decodersetnotifyproc mxr 3.2 and later sec_asn1decoderstart mxr 3.2 and lat...
...oderstart mxr 3.2 and later sec_asn1decoderupdate mxr 3.2 and later sec_asn1encode mxr 3.2 and later sec_asn1encodeinteger mxr 3.2 and later sec_asn1encodeitem mxr 3.2 and later sec_asn1encoderabort mxr 3.9 and later sec_asn1encoderclearnotifyproc mxr 3.2 and later sec_asn1encoderclearstreaming mxr 3.2 and later sec_asn1encodercleartakefrombuf mxr 3.2 and later sec_asn1encoderfinish mxr 3.2 and later sec_asn1encodersetnotifyproc mxr 3.2 and later sec_asn1encodersetstreaming mxr 3.
Rhino Debugger
ino javascript engine includes a source-level debugger for debugging javascript scripts. the debugger is itself a java program which you may run as java org.mozilla.javascript.tools.debugger.main [options] [filename.js] [script-arguments] where the options are the same as the shell. the rhino javascript debugger can debug scripts running in multiple threads and provides facilities to set and clear breakpoints, control execution, view variables, and evaluate arbitrary javascript code in the current scope of an executing script. console window the debugger redirects the system.out, system.in, and system.err streams to an internal javascript console window which provides an editable command line for you to enter javascript code and view system output. the console window maintains a histor...
...e stack the lower-left (dockable) pane in the debugger main window contains a combo-box labeled "context:" which displays the current stack of the executing script. you may move up and down the stack by selecting an entry in the combo-box. when you select a stack frame the variables and watch windows are updated to reflect the names and values of the variables visible at that scope. setting and clearing breakpoints the main desktop of the debugger contains file windows which display the contents of each script you are debugging. you may set a breakpoint in a script by doing one of the following: place the cursor on the line at which you want to set a breakpoint and right-click with the mouse. this action will display a pop-up menu. select the set breakpoint menu item. simply single-cl...
...e line at which you want to set a breakpoint and right-click with the mouse. this action will display a pop-up menu. select the set breakpoint menu item. simply single-click on the line number of the line at which you want to set a breakpoint. if the selected line contains executable code a red dot will appear next to the line number and a breakpoint will be set at that location. you may clear breakpoint in a script by doing one of the following: place the cursor on the line at which you want to clear a breakpoint and right-click with the mouse. this action will display a pop-up menu. select the clear breakpoint menu item. simply single-click on the red dot or the line number of the line at which you want to clear a breakpoint. the red dot will disappear and the breakpoint ...
... viewing variables the lower-left (dockable) pane in the debugger main window contains a tab-pane with two tabs, labeled "this" and "locals". each pane contains a tree-table which displays the properties of the current object and currently visible local variables, respectively. ...
SpiderMonkey 1.8.5
js_newfunctionbyid body new c++ helpers while jsapi remains a c api, the engine is now implemented in c++. some c++ helpers have been introduced into the api, to help embedders writing c++ projects. please note that spidermonkey reserves the js:: namespace for itself. ...
...elf. ...
... jsautocheckrequest jsautoentercompartment js::anchor<> js::call obsolete apis js_clearnewbornroots js_enterlocalrootscope js_leavelocalrootscope js_leavelocalrootscopewithresult js_forgetlocalroot js_newgrowablestring deleted apis js_addnamedroot – use js_add*root js_addnamedrootrt – use js_add*root js_addroot – use js_add*root js_clearnewbornroots – no longer needed js_clearoperationcallback js_clearregexproots js_decompilescript js_destroyscript js_enterlocalrootscope js_executescriptpart js_forgetlocalroot js_getfunctionname js_getoperationlimit js_getscriptobject js_getstringbytes js_getstringchars js_isassigning js_leavelocalrootscope js_leavelocalrootscopewithresult js_newdouble js_newdoublevalue js_newscriptobject js_newstring js_poparguments...
...replacing the branch callback, in anticipation of the addition of the tracing jit (tracemonkey). the interface was finalized only after js 1.8.0 shipped, with bug 477187. the primary change in this interface is that it no longer counts operations; embedders are expected find another mechanism (such as a watchdog thread) to trigger regular callbacks, via js_triggeroperationcallback. regexp apis js_clearregexpstatics, js_newregexpobject, js_newregucexpobject, and js_setregexpinput now receive a pointer to the global object. this change was made in bug 571355 to move the regexp statics out of the context, to simplify cross compartment wrappers. property accessors js_propertystub, js_resolvestub, and user-defined functions of type jspropertyop (e.g. getters and setters) changed from passing jsvals ...
Observer Notifications
l be read completely from the cache. headers are available on the channel. http-on-examine-merged-response called instead of http-on-examine-response when a response will be read partially from cache, and partially from the network (http 206 or 304 response). headers are available on the channel. ...
...ly from cache, and partially from the network (http 206 or 304 response). headers are available on the channel. cookies these topics indicate whenever a cookie has been changed (added, changed, cleared, or deleted) or its setting rejected by the browser. see nsicookieservice for details. topic description cookie-changed called upon a cookie change (added, changed, cleared, or deleted) cookie-rejected called when the setting of a cookie was rejected by the browser (per the user's preferences) http-on-response-set-cookie this is fired only when a cookie is created due to the presence of set-cookie header in the response header of any network request. this notification will come only after the "http-on-examine-response" is fire...
... topic description download-manager-ui-done called when the list of downloads in the download manager windows finishes updating. this can happen multiple times, such as when the window first opens, when multiple items are removed, and when entering private browsing mode. download-manager-remove-download called when a download of the list is removed or all the list is cleared. the subject will be the download id wrapped in nsisupportspruint32, for one download removed, or null for multi download remove, for example when the download list is cleared. extension manager note: these notifications are no longer available starting with gecko 2.0, instead use addonmanager.addaddonlistener() to receive similar events. this topic indicates when the extension manag...
...aded a frame script into a tab using a browser message manager, and the user closes the tab. the frame script is unloaded and the browser message manager disconnects from it. by listening for message-manager-disconnect you will be informed when this happens. permission manager topic subject data description perm-changed nsipermission "deleted"/"added"/"changed"/"cleared" this notification is sent when a permission changes. the subject of the notification is the permission object. context menu topic subject data description content-contextmenu an object containing two properties: event the event that triggered the context menu. addoninfo an empty object that add-ons can use to...
nsIDOMGeoGeolocation
olocation = components.classes["@mozilla.org/geolocation;1"] .getservice(components.interfaces.nsidomgeogeolocation); note: if nsidgeogeolocation throws an exception when importing, try using this: var geolocation = components.classes["@mozilla.org/geolocation;1"] .getservice(components.interfaces.nsisupports); method overview void clearwatch(in unsigned short watchid); void getcurrentposition(in nsidomgeopositioncallback successcallback, [optional] in nsidomgeopositionerrorcallback errorcallback, [optional] in nsidomgeopositionoptions options); unsigned short watchposition(in nsidomgeopositioncallback successcallback, [optio...
...ck successcallback, [optional] in nsidomgeopositionerrorcallback errorcallback, [optional] in nsidomgeopositionoptions options); attributes attribute type description lastposition nsidomgeoposition the most recently retrieved location as seen by the provider. may be null. read only. methods clearwatch() when the clearwatch() method is called, the watch() process stops calling for new position identifiers and cease invoking callbacks. void clearwatch( in unsigned short watchid ); parameters none. getcurrentposition() acquires the user's current position via a new position object. if this fails, errorcallback is invoked with an nsidomgeopositionerror argument. void getcurrentposition( i...
...e. errorcallback an nsidomgeopositionerrorcallback that is called if an error occurs while retrieving the position; this parameter is optional. options an nsidomgeopositionoptions object specifying options; this parameter is optional. watchposition() similar to getcurrentposition(), except it continues to call the callback with updated position information periodically until clearwatch() is called. unsigned short watchposition( in nsidomgeopositioncallback successcallback, [optional] in nsidomgeopositionerrorcallback errorcallback, [optional] in nsidomgeopositionoptions options ); parameters successcallback an nsidomgeopositioncallback that is to be called whenever new position information is available. errorcallback an nsidomgeopositionerrorcallb...
... ...
nsIDOMStorage
ey-value pairs, which may be retrieved, modified and removed as needed. a key may only exist once within a storage object, and only one value may be associated with a particular key. keys are stored in a particular order with the condition that this order not change by merely changing the value associated with a key, but the order may change when a key is added or removed. ...
...getitem() returns from session storage the data corresponding to the specified key. domstring getitem( in domstring key ); parameters key the key for which data should be returned. ...
...getitem() returns from session storage the data corresponding to the specified key. domstring getitem( in domstring key ); parameters key the key for which data should be returned. ...
...getitem() returns from session storage the data corresponding to the specified key. domstring getitem( in domstring key ); parameters key the key for which data should be returned. return value an nsidomstorageitem object describing the data corresponding to the specified key, or null if no data exists for the given key. ...
nsIDOMStorage2
only be accessed by the same origin that created the items in the first place. a dom window's local storage object can be retrieved from the window's localstorage attribute. dom/public/idl/storage/nsidomstorage2.idlscriptable please add a summary to this article. ...
...getitem() returns from local storage the data corresponding to the specified key. ...
...getitem() returns from local storage the data corresponding to the specified key. domstring getitem( in domstring key ); parameters key the key for which data should be returned. ...
...getitem() returns from local storage the data corresponding to the specified key. ...
nsIMsgDatabase
iptable please add a summary to this article. ...
... void listalloffli...
...folderdbclosed() void forcefolderdbclosed(in nsimsgfolder afolder); parameters afolder close() void close(in boolean aforcecommit); parameters aforcecommit commit() void commit(in nsmsgdbcommit committype); parameters committype forceclosed() force closed is evil, and we should see if we can do without it. in 4.x, it was mainly used to remove corrupted databases. void forceclosed(); clearcachedhdrs() void clearcachedhdrs(); resethdrcachesize() void resethdrcachesize(in unsigned long size); getmsghdrforkey() nsimsgdbhdr getmsghdrforkey(in nsmsgkey key); parameters key getmsghdrformessageid() nsimsgdbhdr getmsghdrformessageid(in string messageid); parameters messageid containskey() returns whether or not this database contains the given key. boolean containskey(in nsmsg...
...stener instigator); applyretentionsettings() purge unwanted message headers and/or bodies. if deleteviafolder is true, we'll call nsimsgfolder.deletemessages() to delete the messages. otherwise, we'll just delete them from the db. void applyretentionsettings(in nsimsgretentionsettings amsgretentionsettings, in boolean adeleteviafolder); hasnew() boolean hasnew(); clearnewlist() void clearnewlist(in boolean notify); addtonewlist() void addtonewlist(in nsmsgkey key); startbatch() batching - can be used to cache file stream for local mail, and perhaps to use the mdb batching mechanism as well. void startbatch(); endbatch() void endbatch(); getofflineopforkey() offline operations - we could move these into an offline operation interface but it would have to...
nsIMsgIncomingServer
nsimsgincomingserver mailnews/base/public/nsimsgincomingserver.idlscriptable ??? add brief description of interface ??? ...
... nsimsgincomingserver mailnews/base/public/nsimsgincomingserver.idlscriptable ??? add brief description of interface ??? ...
...oolean read only. type acstring protocol type, that is "pop3", "imap", "nntp", "none", and so on. used to construct urls. username acstring userid to log into the server. ...
...name acstring userid to log into the server. usesecauth boolean valid boolean constants constant value description defaultsocket 0 trytls 1 alwaysusetls 2 usessl 3 keepdups 0 deletedups 1 movedupstotrash 2 markdupsread 3 methods clearallvalues() this is really dangerous. this destroys all pref values do not call this unless you know what you're doing! void clearallvalues(); parameters none. exceptions thrown missing exception missing description cleartemporaryreturnreceiptsfilter() if sent folder pref is changed we need to clear the temporary return receipt filter so that the new return receipt filter can be recreated (by configuretemporaryreturnreceiptsfilter()). void cleartemporaryreturnreceiptsfilter(); parameters none. exceptions thrown missing ...
nsIMsgWindow
illa.org/messenger/msgwindow;1. to create an instance, use: msgwindow = components.classes["@mozilla.org/messenger/msgwindow;1"] .createinstance(components.interfaces.nsimsgwindow); in thunderbird the default message window is stored in the global variable msgwindow. method overview void displayhtmlinmessagepane(in astring title, in astring body, in boolean clearmsghdr); void stopurls(); void closewindow(); attributes attribute type description windowcommands nsimsgwindowcommands this allows the backend code to send commands to the ui, such as clearmsgpane. statusfeedback nsimsgstatusfeedback this allows the backend code to send stat...
... this is 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...
...bal 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 specifying the html. void displayhtmlinmessagepane(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 nsiwebnavig...
...ing 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 all of our objects have let go of it. this forces a release. it clears out the content listener, the windowcommands, the statusfeedback and the docshell objects. void closewindow(); remarks see also ...
nsINavBookmarksService
cked if it is bookmarked or not. return value native code only!getbookmarkfolderstarray 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. tarray version of getbookmarkfolders() for ease of use in c++ code. pass in a reference to a tarray; it will get cleared and filled with the resulting list of folder ids. void getbookmarkfolderstarray( in nsiuri auri, in print64array aresult ); parameters auri aresult returns an nsiuri representing the uri whose bookmark is to be retrieved. if there is no bookmarked page found, it will return null. this method retrieves the list of bookmark ids that contain the given uri. void getbookmarkidsf...
...ode only!getbookmarkidsforuritarray obsolete since gecko 2.0 (firefox 4 / thunderbird 3.3 / seamonkey 2.1)this feature is obsolete. although it may still work in some browsers, its use is discouraged since it could be removed at any time. try to avoid using it. this method is a tarray version of getbookmarkidsforuri() for ease of use in c++ code. pass in a reference to a tarray; it will get cleared and filled with the resulting list of folder ids. void getbookmarkidsforuritarray( in nsiuri auri, in print64array aresult ); parameters auri the uri whose list of bookmark ids is to be retrieved. aresult the list of bookmark ids. getbookmarkuri() this method retrieves the uri for a bookmark item. nsiuri getbookmarkuri( in long long aitemid ); parameters aitemid the id ...
...9 the uri of the item whose title should be updated. aitemid the id of the item whose title should be updated. atitle the new title for the bookmark. will be truncated to title_length_max. setkeywordforbookmark() obsolete since gecko 40.0 note: bug 1187119 provides an alternative for this method. this method associates the given keyword with the given bookmark. use an empty keyword to clear the keyword associated with the uri. in both of these cases, succeeds but does nothing if the url/keyword is not found. void setkeywordforbookmark( in long long aitemid, in astring akeyword ); parameters aitemid the item (bookmark) that needs to be associated with the keyword. akeyword the keyword that needs to be associated with the item (bookmark). setkeywordforuri() ...
... akeyword ); parameters aitemid the item (bookmark) that needs to be associated with the keyword. akeyword the keyword that needs to be associated with the item (bookmark). setkeywordforuri() obsolete since gecko 1.9 (firefox 3) note: bug 1187119 provides an alternative for this method. associates the given keyword with the given uri. use an empty keyword to clear the keyword associated with the uri. use an empty uri to clear the uri associated with that keyword. in both of these cases, succeeds but does nothing if the url/keyword is not found. when setting a keyword (both uri and keyword are specified), the uri must be bookmarked for the keyword to be persistent. void setkeywordforuri( in nsiuri uri, in astring keyword ); parameters uri the ur...
nsITelemetry
fox 7.0 / thunderbird 7.0 / seamonkey 2.4) implemented by: @mozilla.org/base/telemetry;1 as a service: let telemetry = components.classes["@mozilla.org/base/telemetry;1"] .getservice(components.interfaces.nsitelemetry); method overview jsval gethistogrambyid(in acstring id); jsval snapshothistograms(in uint32_t adataset, in boolean asubsession, in boolean aclear); jsval getkeyedhistogrambyid(in acstring id); void capturestack(in acstring name); jsval snapshotcapturedstacks([optional] in boolean clear); nsisupports getloadedmodules(); jsval snapshotkeyedhistograms(in uint32_t adataset, in boolean asubsession, in boolean aclear); void sethistogramrecordingenabled(in acstring id, in boolean enabled); ...
...enabled); void asyncfetchtelemetrydata(in nsifetchtelemetrydatacallback acallback); double mssinceprocessstart(); void scalaradd(in acstring aname, in jsval avalue); void scalarset(in acstring aname, in jsval avalue); void scalarsetmaximum(in acstring aname, in jsval avalue); jsval snapshotscalars(in uint32_t adataset, [optional] in boolean aclear); void keyedscalaradd(in acstring aname, in astring akey, in jsval avalue); void keyedscalarset(in acstring aname, in astring akey, in jsval avalue); void keyedscalarsetmaximum(in acstring aname, in astring akey, in jsval avalue); jsval snapshotkeyedscalars(in uint32_t adataset, [optional] in boolean aclear); void clearscalars(); test only voi...
... aclear); void clearscalars(); test only void flushbatchedchildtelemetry(); void recordevent(in acstring acategory, in acstring amethod, in acstring aobject, [optional] in jsval avalue, [optional] in jsval extra); void seteventrecordingenabled(in acstring acategory, in boolean aenabled); jsval snapshotevents(in uint32_t adataset, [optional] in boolean aclear); void registerevents(in acstring acategory, in jsval aeventdata); void registerscalars(in acstring acategoryname, in jsval ascalardata); void clearevents(); test only attributes attribute type description canrecordbase boolean a flag indicating if telemetry can record base data (fhr data). this is true if the fhr data reporting se...
...s the following functions: add(key, [optional] value) - adds an integer value to the appropriate bucket. for count histograms providing the value is optional. snapshot([optional] key) - returns a snapshot of the keyed histogram or (if key is provided) the snapshot of the contained histogram with that key. keys() - returns an array with the string keys of the currently registered histograms. clear() - clear out the registered histograms and keys. example you can find detailed information on adding a new telemetry probe and recording telemetry data at adding a new telemetry probe [en-us]. see also bug 649502 - expose histograms to js bug 585196 - telemetry infrastructure bug 668312 - report only probes defined in histograms.json bug 1069874 - add keyed histogram types bug 142645...
nsITreeSelection
layout/xul/base/src/tree/public/nsitreeselection.idlscriptable this interface is used by the tree widget to get information about what is selected. ...
... layout/xul/base/src/tree/public/nsitreeselection.idlscriptable this interface is used by the tree widget to get information about what is selected. ...
...ngle boolean this attribute is a boolean indicating single selection. read only. tree nsitreeboxobject the tree widget for this selection. methods adjustselection() called when the row count changes to adjust selection indices. void adjustselection( in long index, in long count ); parameters index index of the change. count number of rows changed. clearrange() clears the range. void clearrange( in long startindex, in long endindex ); parameters startindex index to clearing at. endindex index to stop clearing at. clearselection() clears the selection. void clearselection(); parameters none. getrangeat() returns two objects whose value properties represent the minimum and maximum indices of the given selection range. see th...
...lue rangedselect() select the range specified by the indices. void rangedselect( in long startindex, in long endindex, in boolean augment ); parameters startindex index to start selecting at. endindex index to stop selecting at. this parameter is inclusive; to select one item, set endindex == startindex. augment if true, the range is added to the selection without clearing out anything else. if false, everything is cleared except for the specified range. select() deselect all rows and select the row at the specified index. void select( in long index ); parameters index index of the row to select. selectall() selects all rows. void selectall(); parameters none. timedselect() perform a timed select. void timedselect( in long index, in long delay...
nsIXPConnect
changed in gecko 2.0 (firefox 4 / thunderbird 3.3 / seamonkey 2.1) to access the xpconnect service, use code like this: nsresult rv; nscomptr<nsixpconnect> xpconnect = do_getservice(nsixpconnect::getcid(), &rv); if (ns_succeeded(rv)) { /* use the object */ } method overview void addjsholder(in voidptr aholder, in nsscriptobjecttracerptr atracer); native code only! void clearallwrappednativesecuritypolicies(); nsixpconnectjsobjectholder createsandbox(in jscontextptr cx, in nsiprincipal principal); native code only! nsistackframe createstackframelocation(in pruint32 alanguage, in string afilename, in string afunctionname, in print32 alinenumber, in nsistackframe acaller); void debugdump(in short depth); void debugdumpevalinjsstackfr...
... nsaxpcnativecallcontextptr read only. deferreleasesuntilaftergarbagecollection prbool obsolete since gecko 1.9 pendingexception nsiexception constants constant value description init_js_standard_classes 1 << 0 flag_system_global_object 1 << 1 omit_components_object 1 << 2 xpc_xow_clearscope 1 tells updatexows() to clear the scope of all of the xows it finds. obsolete since gecko 2.0 methods native code only!addjsholder root js objects held by aholder. void addjsholder( in voidptr aholder, in nsscriptobjecttracerptr atracer ); parameters aholder the object that hold the js objects that should be rooted. atracer missing description exceptions thro...
...cope of all of the xows it finds. obsolete since gecko 2.0 methods native code only!addjsholder root js objects held by aholder. void addjsholder( in voidptr aholder, in nsscriptobjecttracerptr atracer ); parameters aholder the object that hold the js objects that should be rooted. atracer missing description exceptions thrown missing exception missing description clearallwrappednativesecuritypolicies() void clearallwrappednativesecuritypolicies(); parameters none. exceptions thrown missing exception missing description native code only!createsandbox create a sandbox for evaluating code in isolation using evalinsandboxobject(). nsixpconnectjsobjectholder createsandbox( in jscontextptr cx, in nsiprincipal principal ); parameters cx a cont...
... parameters none. exceptions thrown missing exception missing description native code only!updatexows obsolete since gecko 2.0 (firefox 4 / thunderbird 3.3 / seamonkey 2.1)this feature is obsolete. although it may still work in some browsers, its use is discouraged since it could be removed at any time. try to avoid using it. performs an operation over all of |object|'s xows such as clearing their scopes or updating their concept of the current principal. void updatexows( in jscontextptr ajscontext, in nsixpconnectwrappednative aobject, in pruint32 away ); parameters ajscontext a context to use to perform js operations. aobject which xpcwrappednative we should find the xows for. away what operation to perform. exceptions thrown missing exception missing desc...
Console messages - Firefox Developer Tools
ror is executed more than once, it is only logged once and this counter appears to indicate how many times it was encountered. filename and line number for javascript, css and console api messages, the message can be traced to a specific line of code. the console then provides a link to the filename and line number that generated the message. by default, the console is cleared each time you navigate to a new page or reload the current page. to override this behavior, enable persist logs in the console settings menu (gear icon). the context menu options listed below are available on all message categories. additional context menu options are described in the subsection for the message category they apply to. copy message copies the selected message to the clipboar...
...discussed here, or are interested in contributing, check out the metabug and its dependencies. logging messages logged from shared workers, service workers, add-ons, and chrome workers are not shown by default. use the filtering feature to show them. the logging category includes messages logged using the console api. ...
...tton, not the requests button. filtering by text to see only messages that contain a specific string, type in the text box labeled "filter output". for example, if you entered the string img into the text box, you would have a list something like this: a small "x" icon appears at the right end of the text box when you have entered a string on which to filter the output. click the "x" icon to clear the filter and show the entire list again. you can negate a text search by prefixing it with the - character. for example, -img shows only items that do not contain the string img. filtering with regular expressions you can also use a valid regular expression to filter the console output. for example, the following video shows the results when filtering on two simple regular expressions: /(coo...
... regular expressions you can also use a valid regular expression to filter the console output. for example, the following video shows the results when filtering on two simple regular expressions: /(cool|rad)/ and /(cool)/. you can negate a regular expression search by prefixing it with the - character. for example, -/(cool|rad)/ shows only items that do not match the expression /(cool|rad)/. clearing the log finally, you can use the trashcan icon on the left to clear the contents of the console. when you clear the console, the console cache is also cleared. this prevents errors that have already been loged from reappearing when you reopen the console. ...
Drawing shapes with canvas - Web APIs
all other shapes must be created by combining one or more paths. luckily, we have an assortment of path drawing functions which make it possible to compose very complex shapes. first let's look at the rectangle. there are three functions that draw rectangles on the canvas: fillrect(x, y, width, height) draws a filled rectangle. strokerect(x, y, width, height) draws a rectangular outline. clearrect(x, y, width, height) clears the specified rectangular area, making it fully transparent. each of these three functions takes the same parameters. x and y specify the position on the canvas (relative to the origin) of the top-left corner of the rectangle. width and height provide the rectangle's size. below is the draw() function from the previous page, but now it is making use of these th...
...nction from the previous page, but now it is making use of these three functions. rectangular shape example <html> <body onload="draw();"> <canvas id="canvas" width="150" height="150"></canvas> </body> </html> function draw() { var canvas = document.getelementbyid('canvas'); if (canvas.getcontext) { var ctx = canvas.getcontext('2d'); ctx.fillrect(25, 25, 100, 100); ctx.clearrect(45, 45, 60, 60); ctx.strokerect(50, 50, 50, 50); } } this example's output is shown below. screenshotlive sample the fillrect() function draws a large black square 100 pixels on each side. the clearrect() function then erases a 60x60 pixel square from the center, and then strokerect() is called to create a rectangular outline 50x50 pixels within the cleared square. in upcoming pages...
... unlike the path functions we'll see in the next section, all three rectangle functions draw immediately to the canvas. ...
... complex than the ones we've seen above. it draws 12 different arcs all with different angles and fills. the two for loops are for looping through the rows and columns of arcs. for each arc, we start a new path by calling beginpath(). in the code, each of the parameters for the arc is in a variable for clarity, but you wouldn't necessarily do that in real life. the x and y coordinates should be clear enough. radius and startangle are fixed. the endangle starts at 180 degrees (half a circle) in the first column and is increased by steps of 90 degrees, culminating in a complete circle in the last column. the statement for the clockwise parameter results in the first and third row being drawn as clockwise arcs and the second and fourth row as counterclockwise arcs. finally, the if statement mak...
Multi-touch interaction - Web APIs
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 pointermoves. // // this function sets the target element's border to "dashed" to visually // indicate the target received a move event. if (logevents) lo...
... and pointerout events. function pointerup_handler(ev) { if (logevents) log(ev.type, ev); // remove this touch point from the cache and reset the target's // background and border remove_event(ev); update_background(ev); ev.target.style.border = "1px solid black"; } application ui the application uses <div> elements for the touch areas and provides buttons to enable logging and to clear the log. to prevent the browser's default touch behavior from overriding this application's pointer handling, the touch-action property is applied to the <body> element. <body onload="init();" style="touch-action:none"> <div id="target1"> tap, hold or swipe me 1</div> <div id="target2"> tap, hold or swipe me 2</div> <div id="target3"> tap, hold or swipe me 3</div> <!-- ui for logging/debug...
...handling, the touch-action property is applied to the <body> element. <body onload="init();" style="touch-action:none"> <div id="target1"> tap, hold or swipe me 1</div> <div id="target2"> tap, hold or swipe me 2</div> <div id="target3"> tap, hold or swipe me 3</div> <!-- ui for logging/debugging --> <button id="log" onclick="enablelog(event);">start/stop event logging</button> <button id="clearlog" onclick="clearlog(event);">clear the log</button> <p></p> <output></output> </body> miscellaneous functions these functions support the application but aren't directly involved with the event flow. cache management these functions manage the global event caches evcache1, evcache2 and evcache3. function get_cache(ev) { // return the cache for this event's target element switch(ev.tar...
...e event flow). ...
SVGLengthList - Web APIs
the svglengthlist defines a list of svglength objects. an svglengthlist object can be designated as read only, which means that attempts to modify the object will result in an exception being thrown. ...
...numberofitems readonly unsigned long length normative document svg 1.1 (2nd edition) properties name type description numberofitems unsigned long the number of items in the list. length unsigned long the number of items in the list. ...
...nly unsigned long length normative document svg 1.1 (2nd edition) properties name type description numberofitems unsigned long the number of items in the list. length unsigned long the number of items in the list. ...
...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. ...
SVGNumberList - Web APIs
svgnumberlist defines a list of svgnumber objects. an svgnumberlist object can be designated as read only, which means that attempts 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. ...
...mberofitems readonly unsigned long length normative document svg 1.1 (2nd edition) properties name type description numberofitems unsigned long the number of items in the list. length unsigned long the number of items in the list. ...
...y unsigned long length normative document svg 1.1 (2nd edition) properties name type description numberofitems unsigned long the number of items in the list. length unsigned long the number of items in the list. ...
...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. ...
SVGStringList - Web APIs
svg string list interface the svgstringlist 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. ...
...th normative document svg 1.1 (2nd edition) properties name type description numberofitems unsigned long the number of items in the list. length unsigned long a mirror of the value in numberofitems, for consistency with other interfaces. ...
...ormative document svg 1.1 (2nd edition) properties name type description numberofitems unsigned long the number of items in the list. length unsigned long a mirror of the value in numberofitems, for consistency with other interfaces. ...
...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. ...
SVGTransformList - Web APIs
rmlist defines a list of svgtransform objects. an svgtransformlist object can be designated as read only, which means that attempts to modify the object will result in an exception being thrown. ...
...mberofitems readonly unsigned long length normative document svg 1.1 (2nd edition) properties name type description numberofitems unsigned long the number of items in the list. length unsigned long the number of items in the list. ...
...y unsigned long length normative document svg 1.1 (2nd edition) properties name type description numberofitems unsigned long the number of items in the list. length unsigned long the number of items in the list. ...
...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. ...
A basic 2D WebGL animation example - Web APIs
nto the message that gets generated. the actual error details are obtained by calling gl.getshaderinfolog(). finally, the compiled shader is returned to the caller (which is the buildshaderprogram() function. drawing and animating the scene the animatescene() function is called to render each animation frame. ...
...the actual error details are obtained by calling gl.getshaderinfolog(). finally, the compiled shader is returned to the caller (which is the buildshaderprogram() function. drawing and animating the scene the animatescene() function is called to render each animation frame. ...
... next, the current rotation vector is computed by converting the current rotation in degrees (currentangle) into radians, then setting the first component of the rotation vector to the sine...
...taangle = ((currenttime - previoustime) / 1000.0) * degreespersecond; currentangle = (currentangle + deltaangle) % 360; previoustime = currenttime; animatescene(); }); } the first thing that needs to be done in order to draw a frame of the animation is to clear the background to the desired color. in this case, we set the viewport based on the size of the <canvas>, call clearcolor() to set the color to use when clearing content, then we clear the buffer with clear(). next, the current rotation vector is computed by converting the current rotation in degrees (currentangle) into radians, then setting the first component of the rotation vector to the sine of that value and the second component to the cosine. the currentrotation vector is now the location of the point on...
Basic scissoring - Web APIs
« previousnext » in this example, we see how to draw simple rectangles and squares using webgl scissoring operations. scissoring establishes a clipping region outside which drawing will not occur. clearing the drawing buffer when scissoring applies this is a simple demonstration of a rendering with scissor(). although the clear() drawing command writes the clear color (set by clearcolor()) to all pixels in the drawing buffer, scissor() defines a mask that only allows pixels inside the specified rectangular area to be updated. this is a good opportunity to talk about the difference between pixels and fragments. a pixel is a picture element (in practice, a point) on the screen, or a single element of the drawing buffer, that area in memory that holds your pixel data (such as ...
...ng. 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 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 s...
... enable() to activate many other features of webgl; hence, the use of the scissor_test constant as an argument in this case). this again demonstrates the typical order of commands in webgl. we first tweak webgl state. in this case, enabling the scissor test and establishing a rectangular mask. only when the webgl state has been satisfactorily tweaked, we execute the drawing command (in this case, clear()) that starts the processing of fragments down the graphics pipeline. <p>result of of scissoring.</p> <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; } window.addeventlistener("load", function s...
...xperimental-webgl"); if (!gl) { paragraph.innerhtml = "failed to get webgl context. " + "your browser or device may not support webgl."; return; } gl.viewport(0, 0, gl.drawingbufferwidth, gl.drawingbufferheight); // enable scissoring operation and define the position and // size of the scissoring area. gl.enable(gl.scissor_test); gl.scissor(40, 20, 60, 130); // clear the drawing buffer solid yellow. gl.clearcolor(1.0, 1.0, 0.0, 1.0); gl.clear(gl.color_buffer_bit); }, false); the source code of this example is also available on github. « previousnext » ...
Color masking - Web APIs
ome tinted glass or color filter. so, by masking off the blue and green channels, you are only allowing the red component of pixels to be updated, and therefore it is as if you were looking through a red tinted glass. color masking allows us to demonstrate some basics of color theory. by masking off some channel(s), we are in fact biasing the displayed colors towards the complementary color. so, clearly masking both blue and red, would give us shades of green. masking only the blue channel would give us shades of yellow (including shades of orange, brown, olive and yellow-green), the complementary of blue. similarly, masking only green would give us shades of magenta (also purples, crimsons, and so on), and masking only red would give shades of cyan (also sea greens, blues, and so on). note t...
...image. alternatively, you may use the rgb components for color, but the alpha component for some custom pixel data of your invention. finally, color masking teaches us that webgl is not only a state machine, it is also a graphics pipeline. this means that graphics operations in webgl are done in a certain order, where the output of each operation serves as the input of the next. so, for example, clearing operation sets the value of each pixel to the chosen clear color. masking occurs later in the pipeline, and modifies the pixel color value, so the final result on the screen is that of the clear color, tinted by the color mask. <p>tinting the displayed colors with color masking.</p> <canvas>your browser does not seem to support html5 canvas.</canvas> <button id="red-toggle">on</button> ...
... « previousnext » ...
... « previousnext » ...
Simple color animation - Web APIs
the user can start, stop and restart the animation by clicking the button. this time we put the webgl function calls within a timer event handler. a click event handler additionally enables the basic user interaction of starting and stopping the animation. ...
... redrawing every second. timer = setinterval(drawanimation, 1000); // give immediate feedback to user after clicking, by // drawing one animation frame. drawanimation(); } function stopanimation(evt) { button.removeeventlistener(evt.type, stopanimation, false); button.addeventlistener("click", startanimation, false); verb.innerhtml="start"; // stop animation by clearing the timer. clearinterval(timer); } // call stopanimation() once to setup the initial event // handlers for canvas and button. stopanimation({type: "click"}); var gl; function drawanimation () { if (!gl) { var canvas = document.getelementbyid("canvas-view"); gl = canvas.getcontext("webgl") ||canvas.getcontext("experimental-webgl"); if (!gl) { ...
... the timer. clearinterval(timer); } // call stopanimation() once to setup the initial event // handlers for canvas and button. stopanimation({type: "click"}); var gl; function drawanimation () { if (!gl) { var canvas = document.getelementbyid("canvas-view"); gl = canvas.getcontext("webgl") ||canvas.getcontext("experimental-webgl"); if (!gl) { clearinterval(timer); alert("failed to get webgl context.\n" + "your browser or device may not support webgl."); return; } gl.viewport(0, 0, gl.drawingbufferwidth, gl.drawingbufferheight); } // get a random color value using a helper function. ...
...l"); if (!gl) { clearinterval(timer); alert("failed to get webgl context.\n" + "your browser or device may not support webgl."); return; } gl.viewport(0, 0, gl.drawingbufferwidth, gl.drawingbufferheight); } // get a random color value using a helper function. var color = getrandomcolor(); // set the webglrenderingcontext clear color to the // random color. gl.clearcolor(color[0], color[1], color[2], 1.0); // clear the context with the newly set color. gl.clear(gl.color_buffer_bit); } // random color helper function. function getrandomcolor() { return [math.random(), math.random(), math.random()]; } }, false); the source code of this example is also available on github. « previous...
WebGL constants - Web APIs
ion('webgl_debug_renderer_info'); var vendor = gl.getparameter(debuginfo.unmasked_vendor_webgl); the webgl tutorial has more information, examples, and resources on how to get started with webgl. table of contents standard webgl 1 constants standard webgl 2 constants webgl extension constants standard webgl 1 constants these constants are defined on the webglrenderingcontext interface. ...
...er(debuginfo.unmasked_vendor_webgl); the webgl tutorial has more information, examples, and resources on how to get started with webgl. table of contents standard webgl 1 constants standard webgl 2 constants webgl extension constants standard webgl 1 constants these constants are defined on the webglrenderingcontext interface. clearing buffers constants passed to webglrenderingcontext.clear() to clear buffer masks. constant name value description depth_buffer_bit 0x00000100 passed to clear to clear the current depth buffer. stencil_buffer_bit 0x00000400 passed to clear to clear the current stencil buffer. color_buffer_bit 0x00004000 passed to clear to clear the current color buffer. rendering primitives constan...
...ack, or front_and_back front_face 0x0b46 passed to getparameter to determine the current value of frontface. should return cw or ccw. depth_range 0x0b70 passed to getparameter to return a length-2 array of floats giving the current depth range. depth_writemask 0x0b72 passed to getparameter to determine if the depth write mask is enabled. depth_clear_value 0x0b73 passed to getparameter to determine the current depth clear value. depth_func 0x0b74 passed to getparameter to get the current depth function. returns never, always, less, equal, lequal, greater, gequal, or notequal. stencil_clear_value 0x0b91 passed to getparameter to get the value the stencil will be cleared to. stencil_func 0x0b92 ...
...epth_pass 0x8803 stencil_back_ref 0x8ca3 stencil_back_value_mask 0x8ca4 stencil_back_writemask 0x8ca5 viewport 0x0ba2 returns an int32array with four elements for the current viewport dimensions. scissor_box 0x0c10 returns an int32array with four elements for the current scissor box dimensions. ...
Viewpoints and viewers: Simulating cameras in WebXR - Web APIs
ing out just the array representing the view matrix. composing multiple transforms if your camera needs to be performing multiple transforms simultaneously, such as zooming and panning at the same time, you can multiply the transform matrices together to compose them into a single matrix that applies both changes at once. see multiplying two matrices in the article matrix math for the web for a clear but readable function that does this or use your preferred matrix math library such as glmatrix to do the work. it's crucial to remember that unlike typical arithmetic, where multiplication is commutative (that is, you get the same answer whether you multiply left to right or right to left), matrix multiplication is not commutative! this is because each transform affects the position of the obje...
...ame) { let adjustedrefspace = applypositionoffsets(xrreferencespace); let pose = frame.getviewerpose(adjustedrefspace); animationframerequestid = frame.session.requestanimationframe(myanimationframecallback); if (pose) { let gllayer = frame.session.renderstate.baselayer; gl.bindframebuffer(gl.framebuffer, gllayer.framebuffer); checkglerror("binding the framebuffer"); gl.clearcolor(0, 0, 0, 1.0); gl.cleardepth(1.0); gl.clear(gl.color_buffer_bit | gl.depth_buffer_bit); checkglerror("clearing the framebuffer"); const deltatime = (time - lastframetime) * 0.001; lastframetime = time; for (let view of pose.views) { let viewport = gllayer.getviewport(view); gl.viewport(viewport.x, viewport.y, viewport.width, viewport.height); check...
...so we don't have to worry about doing it later, by simply calling requestanimationframe() again. now it's time to render the scene. if we did successfully obtain a pose, we get the xrwebgllayer we need to use for rendering from the session's renderstate object's baselayer property. we bind this to webgl's gl.framebuffer target using the webglrenderingcontext method gl.bindframebuffer(). ...
.... if we did successfully obtain a pose, we get the xrwebgllayer we need to use for rendering from the session's renderstate object's baselayer property. we bind this to webgl's gl.framebuffer target using the webglrenderingcontext method gl.bindframebuffer(). then we clear the framebuffer to ensure we're starting with a known state, since our renderer will not be touching every pixel. we set the clear color to opaque black using gl.clearcolor() and the value to clear the depth buffer to to 1.0 by calling the webglrenderingcontext method gl.cleardepth(). then we call the webglrenderingcontext method gl.clear(), which clears the framebuffer (since we include gl.color_buffer_bit in the mask parameter) and the depth buffer (because we include gl.depth_buffer_bit). then we determine how much time ...
XRViewerPose.views - Web APIs
length may potentially vary over the lifetime of the xrsession (for example, if the viewer enables or disables stereo mode on their xr output device). examples in this example—part of the code to render an xrframe, getviewerpose() is called to get an xrviewerpose using the same reference space the code is using as its base reference space. ...
...ing as its base reference space. if a valid pose is returned, the frame is rendered by clearing the backbuffer and then rendering each of the views in the pose; these are most likely the views for the left and right eyes. ...
...ce. if a valid pose is returned, the frame is rendered by clearing the backbuffer and then rendering each of the views in the pose; these are most likely the views for the left and right eyes. ...
...is returned, the frame is rendered by clearing the backbuffer and then rendering each of the views in the pose; these are most likely the views for the left and right eyes. ...
XRViewerPose - Web APIs
uld be computed. the returned xrviewerpose tells you where the viewer is and what direction they're facing at the time at which the frame takes place. examples in this example—part of the code to render an xrframe, getviewerpose() is called to get an xrviewerpose using the same reference space the code is using as its base reference space. ...
...ing as its base reference space. if a valid pose is returned, the frame is rendered by clearing the backbuffer and then rendering each of the views in the pose; these are most likely the views for the left and right eyes. ...
...ce. if a valid pose is returned, the frame is rendered by clearing the backbuffer and then rendering each of the views in the pose; these are most likely the views for the left and right eyes. ...
...is returned, the frame is rendered by clearing the backbuffer and then rendering each of the views in the pose; these are most likely the views for the left and right eyes. ...
<input type="button"> - HTML: Hypertext Markup Language
Web › HTML › Element › input › button
validation buttons don't participate in constraint validation; they have no real value to be constrained. examples the below example shows a very simple drawing app created using a <canvas> element and some simple css and javascript (we'll hide the css for brevity). the top two controls allow you to choose the color and size of the drawing pen. ...
... (we'll hide the css for brevity). the top two controls allow you to choose the color and size of the drawing pen. the button, when clicked, invokes a function that clears the canvas. ...
...elector('.mycanvas'); var width = canvas.width = window.innerwidth; var height = canvas.height = window.innerheight-85; var ctx = canvas.getcontext('2d'); ctx.fillstyle = 'rgb(0,0,0)'; ctx.fillrect(0,0,width,height); var colorpicker = document.queryselector('input[type="color"]'); var sizepicker = document.queryselector('input[type="range"]'); var output = document.queryselector('.output'); var clearbtn = document.queryselector('input[type="button"]'); // covert degrees to radians function degtorad(degrees) { return degrees * math.pi / 180; }; // update sizepicker output value sizepicker.oninput = function() { output.textcontent = sizepicker.value; } // store mouse pointer coordinates, and whether the button is pressed var curx; var cury; var pressed = false; // update mouse pointer ...
...ow.event) ? e.pagex : e.clientx + (document.documentelement.scrollleft ? document.documentelement.scrollleft : document.body.scrollleft); cury = (window.event) ? e.pagey : e.clienty + (document.documentelement.scrolltop ? ...
Alt-Svc - HTTP
Web › HTTP › Headers › Alt-Svc
<protocol-id> the alpn protocol identifier. examples include h2 for http/2 and h3-25 for draft 25 of the http/3 protocol. ...
... <protocol-id> the alpn protocol identifier. examples include h2 for http/2 and h3-25 for draft 25 of the http/3 protocol. ...
... <protocol-id> the alpn protocol identifier. examples include h2 for http/2 and h3-25 for draft 25 of the http/3 protocol. ...
...r of seconds for which the alternative service is considered fresh. if omitted, it defaults to 24 hours. alternative service entries can be cached for up to <max-age> seconds, minus the age of the response (from the age header). if the cached entry expires, the client can no longer use this alternative service for new connections. persist=1optional usually cached alternative service entries are cleared on network configuration changes. use of the persist=1 parameter ensures that the entry is not deleted through such changes. multiple entries can be specified in a single alt-svc header using comma as separator. in that case, early entries are considered more preferable. example alt-svc: h2=":443"; ma=2592000; alt-svc: h2=":443"; ma=2592000; persist=1 alt-svc: h2="alt.example.com:443", h2="...
JavaScript modules - JavaScript
is feature. introducing an example to demonstrate usage of modules, we've created a simple set of examples that you can find on github. these examples demonstrate a simple set of modules that create a <canvas> element on a webpage, and then draw (and report information about) different shapes on the canvas. these are fairly trivial, but have been kept deliberately simple to demonstrate modules clearly. note: if you want to download the examples and run them locally, you'll need to run them through a local web server. basic example structure in our first example (see basic-modules) we have a file structure as follows: index.html main.js modules/ canvas.js square.js note: all of the examples in this guide have basically the same structure; the above should start getting pretty ...
...ts length. reportperimeter() — writes a square's perimeter to a specific report list, given its length. aside — .mjs versus .js throughout this article, we've used .js extensions for our module files, but in other resources you may see the .mjs extension used instead. v8's documentation recommends this, for example. the reasons given are: it is good for clarity, i.e. it makes it clear which files are modules, and which are regular javascript. it ensures that your module files are parsed as a module by runtimes such as node.js, and build tools such as babel. however, we decided to keep to using .js, at least for the moment. to get modules to work correctly in a browser, you need to make sure that your server is serving them with a content-type header that contains a javascri...
...sections of script defined inside modules as opposed to in standard scripts. this is because modules use strict mode automatically. there is no need to use the defer attribute (see <script> attributes) when loading a module script; modules are deferred automatically. modules are only executed once, even if they have been referenced in multiple <script> tags. last but not least, let's make this clear — module features are imported into the scope of a single script — they aren't available in the global scope. therefore, you will only be able to access imported features in the script they are imported into, and you won't be able to access them from the javascript console, for example. you'll still get syntax errors shown in the devtools, but you'll not be able to use some of the debugging t...
...r such as "syntaxerror: redeclaration of import name" (firefox). instead we need to rename the imports so that they are unique: import { name as squarename, draw as drawsquare, reportarea as reportsquarearea, reportperimeter as reportsquareperimeter } from './modules/square.js'; import { name as circlename, draw as drawcircle, reportarea as reportcirclearea, reportperimeter as reportcircleperimeter } from './modules/circle.js'; import { name as trianglename, draw as drawtriangle, reportarea as reporttrianglearea, reportperimeter as reporttriangleperimeter } from './modules/triangle.js'; note that you could solve the problem in the module files instead, e.g. // in square.js export { name as squarename, d...
Canvas code snippets - Archive of obsolete content
= 'string') { canvas = document.getelementbyid(canvas); } if (!(this instanceof canvas2dcontext)) { return new canvas2dcontext(canvas); } this.context = this.ctx = canvas.getcontext('2d'); if (!canvas2dcontext.prototype.arc) { canvas2dcontext.setup.call(this, this.ctx); } } canvas2dcontext.setup = function() { var methods = ['arc', 'arcto', 'beginpath', 'beziercurveto', 'clearrect', 'clip', 'closepath', 'drawimage', 'fill', 'fillrect', 'filltext', 'lineto', 'moveto', 'quadraticcurveto', 'rect', 'restore', 'rotate', 'save', 'scale', 'settransform', 'stroke', 'strokerect', 'stroketext', 'transform', 'translate']; var gettermethods = ['createpattern', 'drawfocusring', 'ispointinpath', 'measuretext', // drawfocusring not currently supported // the follow...
... var canvas = document.createelement('canvas'); canvas.style.width = remotecanvas.canvas_width + 'px'; canvas.style.height = remotecanvas.canvas_height + 'px'; canvas.width = remotecanvas.canvas_width; canvas.height = remotecanvas.canvas_height; var windowwidth = window.innerwidth - 25; var windowheight = window.innerheight; var ctx = canvas.getcontext('2d'); ctx.clearrect(0, 0, remotecanvas.canvas_width, remotecanvas.canvas_height); ctx.save(); ctx.scale(remotecanvas.canvas_width / windowwidth, remotecanvas.canvas_height / windowheight); ctx.drawwindow(remotewindow, 0, 0, windowwidth, windowheight, 'rgb(255, 255, 255)'); ctx.restore(); }; ...
...erts its content to data uri scheme. var canvas = document.createelement('canvas'); var ctxt = canvas.getcontext('2d'); function loadimagefile(url, callback) { var image = new image(); image.src = url; return new promise((accept, reject) => { image.onload = accept; image.onerror = reject; }).then(accept => { canvas.width = this.width; canvas.height = this.height; ctxt.clearrect(0, 0, this.width, this.height); ctxt.drawimage(this, 0, 0); accept(canvas.todataurl()); }); } usage: loadimagefile('myimage.jpg').then(string64 => { alert(string64); }); if you want to get instead the base64 content of a local file using the file <input> element, you must use the filereader object. ...
Code snippets - Archive of obsolete content
let collection = "forms"; components.utils.import("resource://services-sync/main.js"); components.utils.import("resource://services-sync/record.js"); let recordtype = weave.engines.get(collection)._recordobj; let coll = new collection(weave.service.storageurl + collection, recordtype); coll.full = true; coll.recordhandler = function(item) { i...
... = "forms"; components.utils.import("resource://services-sync/main.js"); components.utils.import("resource://services-sync/record.js"); let recordtype = weave.engines.get(collection)._recordobj; let coll = new collection(weave.service.storageurl + collection, recordtype); coll.full = true; coll.recordhandler = function(item) { item.collection = collection; item.decrypt(); console.log(item.cleartext); }; coll.get(); print an individual record let collection = "history"; let id = "guid_goes_here"; components.utils.import("resource://services-sync/main.js"); components.utils.import("resource://services-sync/record.js"); let recordtype = weave.engines.get(collection)._recordobj; let coll = new collection(weave.service.storageurl + collection, recordtype); coll.full = true; coll.ids = [id...
...onents.utils.import("resource://services-sync/main.js"); components.utils.import("resource://services-sync/record.js"); let recordtype = weave.engines.get(collection)._recordobj; let coll = new collection(weave.service.storageurl + collection, recordtype); coll.full = true; coll.ids = [id]; coll.recordhandler = function(item) { item.collection = collection; item.decrypt(); console.log(item.cleartext); }; coll.get(); count types of bookmark records components.utils.import("resource://services-sync/main.js"); components.utils.import("resource://services-sync/record.js"); let deleted = 0; let items = {}; let collection = "bookmarks"; let recordtype = weave.engines.get(collection)._recordobj; let coll = new collection(weave.service.storageurl + collection, recordtype); ...
Space Manager Detailed Design - Archive of obsolete content
* * returns ns_ok if successful, ns_error_invalid_arg if there is no region * tagged with aframe */ nsresult offsetregion(nsiframe* aframe, nscoord dx, nscoord dy); /** * remove the region associated with afrane. * * returns ns_ok if successful and ns_error_invalid_arg if there is no region * tagged with aframe */ nsresult removeregion(nsiframe* aframe); /** * clears the list of regions representing the unavailable space. */ void clearregions(); /** * methods for dealing with the propagation of float damage during * reflow. */ prbool hasfloatdamage() { return !mfloatdamage.isempty(); } void includeindamage(nscoord aintervalbegin, nscoord aintervalend) { mfloatdamage.includeinterval(aintervalbegin + my, aintervalend + my); ...
...(); // accessors prbool isempty() const {return pr_clist_is_empty((prcliststr*)this);} bandrect* head() const {return (bandrect*)pr_list_head(this);} bandrect* tail() const {return (bandrect*)pr_list_tail(this);} // operations void append(bandrect* abandrect) {pr_append_link(abandrect, this);} // remove and delete all the band rects in the list void clear(); }; frameinfo* getframeinfofor(nsiframe* aframe); frameinfo* createframeinfo(nsiframe* aframe, const nsrect& arect); void destroyframeinfo(frameinfo*); void clearframeinfo(); void clearbandrects(); bandrect* getnextband(const bandrect* abandrect) const; void divideband(bandrect* aband, nscoord abottom); prbool canjoinbands(bandrect* aband, band...
...by the specified amount. * * returns ns_ok if successful, ns_error_invalid_arg if there is no region * tagged with aframe */ nsresult offsetregion(nsiframe* aframe, nscoord dx, nscoord dy); /** * remove the region associated with afrane. * * returns ns_ok if successful and ns_error_invalid_arg if there is no region * tagged with aframe */ nsresult removeregion(nsiframe* aframe); /** * clears the list of regions representing the unavailable space. */ void clearregions(); float impact /** * methods for dealing with the propagation of float damage during * reflow. */ prbool hasfloatdamage() { return !mfloatdamage.isempty(); } void includeindamage(nscoord aintervalbegin, nscoord aintervalend) { mfloatdamage.includeinterval(aintervalbegin + my, aintervalend + my); } prbool i...
Venkman Internals - Archive of obsolete content
these notes are written by such readers: as you learn please correct any errors. questions why can't breakpoints be set on some source lines some of the time? sometimes the source has small ticks in the margin for every executable line in my javascript. sometimes these ticks are missing on some or all lines of a file. only lines with tick marks seem to break point properly. venkman asks the js engine which lines are executable. it will mark these with a "tick" as you call it. ...
...t.baselinenumber (one based). the total length of the function is scriptwrapper.jsdscript.lineextent. if you want to get at the pretty printed source text, instead of the actual source text, use scriptwrapper.jsdscript.functionsource. scriptinstance all scriptwrappers are parented by a single scriptinstance, which holds all of the scriptwrappers for a particular url. from here, you can set and clear breakpoints by line number (instead of by program counter), locate a scriptwrapper for a given line number, and do a few other useful things. scriptinstance.functions is a hash of all of the functions in the script instance, keyed by the tag property of the jsdscript. scriptinstance.toplevel is the top-level script for the instance. scriptmanager sometimes the same url is loaded more than once...
...t. scriptinstance.toplevel is the top-level script for the instance. scriptmanager sometimes the same url is loaded more than once in the browser. to deal with this, all scriptinstances are parented by a single scriptmanager. a scriptmanager keeps all of the loaded instances of a particular url in the scriptmanager.instances array, in the order that they were loaded. from here, you can set and clear breakpoints in all instances. scriptmanager.transients is a hash of all of the "transient" scripts from this url, where a transient script is something compiled as a the result of an eval, settimeout, or setinterval. try starting up venkman and type "/watch-expr client.scriptmanagers", make sure to turn on "include functions". this tree should give you a pretty good idea of how it all fits togeth...
statustext - Archive of obsolete content
mozilla doesn't adjust the status bar automatically however. this attribute serves only as a place to keep the text. in firefox, this text is automatically placed in the statusbar for menuitems on the menu bar. ...
...this text is automatically placed in the statusbar for menuitems on the menu bar. ...
...seout="clearstatusmessage()"/> <button label="ping" statustext="ping the server" onmouseover="setstatusmessage(this)" onmouseout="clearstatusmessage()"/> <statusbar> <statusbarpanel id="mystatuspanel" label="" flex="1"/> <spacer flex="1"/> </statusbar> <script> function setstatusmessage(obj){ document.getelementbyid('mystatuspanel').label = obj.getattribute('statustext'); } function clearstatusmessage(obj){ document.getelementbyid('mystatuspanel').label = ''; } </script> see also statusbar and statusbarpanel ...
XUL Questions and Answers - Archive of obsolete content
more documentation on search plugins is available in the search plugins category. is localizing remote xul possible? loading remote dtds for xml documents is currenty not supported in xul. the following bugs were reported on this issue: bug 22942, bug 133698. ...
...ntually be fixed to return the value with the correct type. using the "icon" attribute on a button from xulplanet.com reference: this attribute should be used to set the usage for common buttons. some platforms display these buttons with a small icon indicating their usage. this should be used in place of the image attribute. possible values include: accept, cancel, help, open, save, find, clear, yes, no, apply, close, print, add, remove, refresh, go-forward, go-back, properties, select-font, select-color, network. if you are using a button that matches one of these common usages, use the icon attribute to indicate this. how to use dynamic objects in toolbar there may be a few ways to implement this: by building your menupopup from an rdf datasource, which could be generated on t...
...t from inside a javascript document? use the following snippet of code to reference a js file within a js file: objscriptloader = components.classes["@mozilla.org/moz/jssubscript-loader;1"].getservice(components.interfaces.mozijssubscriptloader); objscriptloader.loadsubscript(strurl); see http://www.xulplanet.com/references/...iptloader.html for more information. too specific questions or unclear answers how do i remove the file location header included in the default printing setting? see http://www.xulplanet.com/references/...ef_iframe.html, the first user note at the bottom. change this line var settings = printutils.getprintsettings(); to this var settings = printutils.getprintsettings().clone(); settings.docurl = " "; // suppress url on printout other options you can modify ar...
listbox - Archive of obsolete content
trols for more information. ...
...utens(), setuserdata additemtoselection( item ) return type: no return value selects the 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 t...
...pe: no return value if offset is positive, adjusts the focused item forward by that many items. if offset is negative, adjusts the focused item backward by that many items. if isselecting is true, then the selection is also adjusted. if isselectingrange is also true, then the new item is selected in addition to any currently selected items. if isselectingrange is false, any existing selection is cleared. items that are hidden are skipped. removeitemat( index ) return type: element removes the child item in the element at the specified index. the method returns the removed item. removeitemfromselection( item ) return type: no return value deselects the specified item without deselecting other items. scrolltoindex( index ) return type: no return value scrolls the el...
richlistbox - Archive of obsolete content
e selection to rich list boxes. ...
...ns(), setuserdata additemtoselection( item ) return type: no return value selects the 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...
...pe: no return value if offset is positive, adjusts the focused item forward by that many items. if offset is negative, adjusts the focused item backward by that many items. if isselecting is true, then the selection is also adjusted. if isselectingrange is also true, then the new item is selected in addition to any currently selected items. if isselectingrange is false, any existing selection is cleared. items that are hidden are skipped. removeitemat( index ) return type: element removes the child item in the element at the specified index. the method returns the removed item. removeitemfromselection( item ) return type: no return value deselects the specified item without deselecting other items. scrolltoindex( index ) return type: no return value scrolls the...
Desktop gamepad controls - Game development
rray. if it is, then the function returns true; false otherwise. next, in the draw() function we do two things — execute the gamepadupdatehandler() function to get the current state of pressed buttons on every frame, and use the gamepadbuttonpressedhandler() function to check the buttons we are interested to see whether they are pressed, and do something if they are: function draw() { ctx.clearrect(0, 0, canvas.width, canvas.height); // ... gamepadupdatehandler(); if(gamepadbuttonpressedhandler(0)) { playery -= 5; } else if(gamepadbuttonpressedhandler(1)) { playery += 5; } if(gamepadbuttonpressedhandler(2)) { playerx -= 5; } else if(gamepadbuttonpressedhandler(3)) { playerx += 5; } if(gamepadbuttonpressedhandl...
...the same goes for the axes information — looping through axes adds the values to the array. received values are assigned to the proper objects and returns the pressed info for debugging purposes. the button.pressed() function detects the actual ...
...epadapi.buttons.layout[b]); } } } var axes = []; if(c.axes) { for(var a=0,x=c.axes.length; a<x; a++) { axes.push(c.axes[a].tofixed(2)); } } gamepadapi.axes.status = axes; gamepadapi.buttons.status = pressed; return pressed; }, the function above clears the buttons cache, and copies their status from the previous frame to the cache. next, the button status is cleared and the new information is added. the same goes for the axes information — looping through axes adds the values to the array. received values are assigned to the proper objects and returns the pressed info for debugging purposes. the button.pressed() function detects the actual button presses: pressed: function(button, hold) { var newpress = false; for(var i=0,s=gamepadapi.buttons.statu...
Finishing up - Game development
lstyle = "#0095dd"; ctx.filltext("lives: "+lives, canvas.width-65, 20); } instead of ending the game immediately, we will decrease the number of lives until they are no longer available. we can also reset the ball and the paddle positions when the player begins with their next life. ...
...and the paddle positions when the player begins with their next life. so, in the draw() function replace the following three lines: alert("game over"); document.location.reload(); clearinterval(interval); // needed for chrome to end game with this, we can add slightly more complex logic to it as given below: lives--; if(!lives) { alert("game over"); document.location.reload(); clearinterval(interval); // needed for chrome to end game } else { x = canvas.width/2; y = canvas.height-30; dx = 2; dy = -2; paddlex = (canvas.width-paddlewidth)/2; } now, when the ball hits the bottom edge of the screen, we're subtracting one life from the lives variable. if there are no lives left, the game is lost; if there are still some lives left, then the position of the ba...
...with requestanimationframe() now let's work on something that is not connected to the game mechanics, but to the way it is being rendered. requestanimationframe helps the browser render the game better than the fixed framerate we currently have implemented using setinterval(). ...
Supporting older browsers - Learn web development
.wrapper { background-color: rgb(79,185,227); padding: 10px; max-width: 400px; display: grid; grid-template-columns: 1fr 1fr 1fr; } .item { float: left; border-radius: 5px; background-color: rgb(207,232,220); padding: 1em; } <div class="wrapper"> <div class="item">item one</div> <div class="item">item two</div> <div class="item">item three</div> </div> note: the clear property also has no effect once the cleared item becomes a grid item, so you could have a layout with a cleared footer, which is then turned into a grid layout. fallback methods there are a number of layout methods which can be used in a similar way to this float example. you can choose the one that makes the most sense for the layout pattern you need to create. float and clear as shown a...
... display: inline-block this method can be used to create column layouts, if an item has display: inline-block set but then becomes a flex or grid item, the inline-block behaviour is ignored. ...
... display: inline-block this method can be used to create column layouts, if an item has display: inline-block set but then becomes a flex or grid item, the inline-block behaviour is ignored. display: table the method of creating css tables described in the introduction to these lessons can be used as a fallback. ...
Functions — reusable blocks of code - Learn web development
). we'll look at using browser apis in more detail in a later module. functions versus methods programmers call functions that are part of objects methods. you don't need to learn about the inner workings of structured javascript objects yet — you can wait until our later module that will teach you all about the inner workings of objects, and how to create your own. for now, we just wanted to clear up any possible confusion of method versus function — you are likely to meet both terms as you look at the available related resources across the web. the built-in code we've made use of so far come in both forms: functions and methods. you can check the full list of the built-in functions, as well as the built-in objects and their corresponding methods here. you've also seen a lot of custom ...
...also seen a lot of custom functions in the course so far — functions defined in your code, not inside the browser. anytime you saw a custom name with parentheses straight after it, you were using a custom function. in our random-canvas-circles.html example (see also the full source code) from our loops article, we included a custom draw() function that looked like this: function draw() { ctx.clearrect(0,0,width,height); for (let i = 0; i < 100; i++) { ctx.beginpath(); ctx.fillstyle = 'rgba(255,0,0,0.5)'; ctx.arc(random(width), random(height), random(50), 0, 2 * math.pi); ctx.fill(); } } this function draws 100 random circles inside a <canvas> element. every time we want to do that, we can just invoke the function with this: draw(); rather than having to write all tha...
...example calls the random() function three times, which is defined by the following code: function random(number) { return math.floor(math.random()*number); } we needed this function because the browser's built-in math.random() function only generates a random decimal number between 0 and 1. we wanted a random whole number between 0 and a specified number. invoking functions you are probably clear on this by now, but just in case ... to actually use a function after it has been defined, you've got to run — or invoke — it. this is done by including the name of the function in the code somewhere, followed by parentheses. function myfunction() { alert('hello'); } myfunction(); // calls the function once anonymous functions you may see functions defined and invoked in slightly differ...
Looping code - Learn web development
eryselector('button'); const canvas = document.queryselector('canvas'); const ctx = canvas.getcontext('2d'); let width = document.documentelement.clientwidth; let height = document.documentelement.clientheight; canvas.width = width; canvas.height = height; function random(number) { return math.floor(math.random()*number); } function draw() { ctx.clearrect(0,0,width,height); for (let i = 0; i < 100; i++) { ctx.beginpath(); ctx.fillstyle = 'rgba(255,0,0,0.5)'; ctx.arc(random(width), random(height), random(50), 0, 2 * math.pi); ctx.fill(); } } btn.addeventlistener('click',draw); </script> </body> </html> you don't have to understand all the code for now, but let's look at the part o...
...uated (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 the condition is no longer true. some curly braces that contain a block of code — this code will be run each time the loop iterates. let's look at a real example so we can visualize what these do more clearly. const cats = ['bill', 'jeff', 'pete', 'biggles', 'jasmin']; let info = 'my cats are called '; const para = document.queryselector('p'); for (let i = 0; i < cats.length; i++) { info += cats[i] + ', '; } para.textcontent = info; this gives us the following output: hidden code 2 <!doctype html> <html> <head> <meta charset="utf-8"> <title>basic for loop example</title> <styl...
...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: loops. conclusion this article has revealed to you the basic concepts behind, and different options available when looping code in javascript. you should now be clear on why loops are a good mechanism for dealing with repetitive code and are raring to use them in your own examples! if there is anything you didn't understand, feel free to read through the article again, or contact us to ask for help. ...
Client-side storage - Learn web development
ll, make local copies of our index.html, style.css, and index-start.js files into a new directory on your local machine. have a look at the files. you'll see that the html is pretty simple: a web site with a header and footer, as well as a main content area that contains a place to display notes, and a form for entering new notes into the database. the css provides some simple styling to make it clearer what is going on. the javascript file contains five declared constants containing references to the <ul> element the notes will be displayed in, the title and body <input> elements, the <form> itself, and the <button>. rename your javascript file to index.js. you are now ready to start adding code to it. database initial set up now let's look at what we have to do in the first place, to act...
... ...
...s 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 already, so we'd probably better define it. add this to your code, below the previous function definition: // define the displaydata() function function dis...
Third-party APIs - Learn web development
ection.appendchild(para); } else { for(var i = 0; i < articles.length; i++) { const article = document.createelement('article'); const heading = document.createelement('h2'); const link = document.createelement('a'); const img = document.createelement('img'); const para1 = document.createelement('p'); const para2 = document.createelement('p'); const clearfix = document.createelement('div'); let current = articles[i]; console.log(current); link.href = current.web_url; link.textcontent = current.headline.main; para1.textcontent = current.snippet; para2.textcontent = 'keywords: '; for(let j = 0; j < current.keywords.length; j++) { const span = document.createelement('span'); span.textcontent...
...= 'keywords: '; for(let j = 0; j < current.keywords.length; j++) { const span = document.createelement('span'); span.textcontent += current.keywords[j].value + ' '; para2.appendchild(span); } if(current.multimedia.length > 0) { img.src = 'http://www.nytimes.com/' + current.multimedia[0].url; img.alt = current.headline.main; } clearfix.setattribute('class','clearfix'); article.appendchild(heading); heading.appendchild(link); article.appendchild(img); article.appendchild(para1); article.appendchild(para2); article.appendchild(clearfix); section.appendchild(article); } } } there's a lot of code here; let's explain it step by step: the while loop is a common pattern used to d...
... each article, and insert each one inside its own <span>, inside a <p>. this was done to make it easy to style each one. we used an if() block (if(current.multimedia.length > 0) { ... }) to check whether each article has any images associated with it (some stories don't.) we display the first image only if it exists (otherwise an error would be thrown). we gave our <div> element a class of "clearfix", so we can easily apply clearing to it. wiring up the pagination buttons to make the pagination buttons work, we will increment (or decrement) the value of the pagenumber variable, and then re-rerun the fetch request with the new value included in the page url parameter. this works because the nytimes api only returns 10 results at a time — if more than 10 results are available, it ...
Ember app structure and componentization - Learn web development
now we need to break up our html code into dynamic components; later we'll turn it into a fully interactive app. looking at the code next to the rendered todo app, there are a number of ways we coul...
...now we need to break up our html code into dynamic components; later we'll turn it into a fully interactive app. looking at the code next to the rendered todo app, there are a number of ways we could decide how to break up...
...n> </div> <input autofocus class="edit" value="todo text"> </li> footer.hbs should be updated to contain the following: <footer class="footer"> <span class="todo-count"> <strong>0</strong> todos left </span> <ul class="filters"> <li> <a href="#">all</a> <a href="#">active</a> <a href="#">completed</a> </li> </ul> <button type="button" class="clear-completed"> clear completed </button> </footer> finally, the contents of application.hbs should be updated so that they call the appropriate components, like so: <section class="todoapp"> <h1>todos</h1> <header /> <todolist /> <footer /> </section> with these changes made, run npm start in your terminal again, then head over to http://localhost:4200 to ensure that t...
Advanced Svelte: Reactivity, lifecycle, accessibility - Learn web development
d={!name} class="btn btn__primary btn__lg">add</button> </form> here we are binding the <input> to the name variable with bind:value={name} and disabling the add button when it is empty (i.e. no text content) using disabled={!name}. we are also taking care of the escape key with on:keydown={e => e.key === 'escape' && oncancel()}. whenever the escape key is pressed we run oncancel(), which just clears up the name variable. now we have to import and use it from inside the todos component, and update the addtodo() function to receive the name of the new todo. add the following import statement below the others inside todos.svelte: import newtodo from './newtodo.svelte' and update the addtodo() function like so: function addtodo(name) { todos = [...todos, { id: newtodoid, ...
... 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 and a short directive like use:selectonfocus that clearly depicts its purpose. and we can achieve this without the need to create a custom wrapper element like textinput, myinput or similar. moreover, you can add as many use:action directives as you want to an element. also, we didn't have to struggle with onmount(), ondestroy() or tick() — the use directive takes care of the component lifecycle for us. other actions improvements in the previous ...
...es using the bind:this={component} directive there's still one accessibility annoyance left. when the user presses the delete button, the focus vanishes. so, the last feature we will be looking at in this article involves setting the focus on the status heading after a todo has been deleted. why the status heading? in this case, the element that had the focus has been deleted, so there's not a clear candidate to receive focus. we've picked the status heading because it's near the list of todos, and it's a way to give a visual feedback about the removal of the task, as well as indicating what's happened to screenreader users. first we'll extract the status heading to its own component. create a new file — components/todosstatus.svelte. add the following contents to it: <scri...
Implementing QueryInterface
it only has one addref. it addrefs the resulting interface, not this, thus following the com-correct way (particularly important in aggregation) it uses nscomtypeinfo<t>::getiid() instead of ktiid thus saving a ...
... it only has one addref. ...
...following the com-correct way (particularly important in aggregation) it uses nscomtypeinfo<t>::getiid() instead of ktiid thus saving a global declaration and global space it uses c 's static_cast, via ns_static_cast, which detects errors when you can't really get to the desired interface. it avoids repeated uses of and assignments to *ainstanceptr, which compilers have trouble optimizing. it clears the result, *ainstanceptr, when returning an error. it generates less code than the typical implementation of queryinterface. it tests for bad input with an ns_assertion, to find logic errors immediately in debug builds. some alternatives the ns_impl_query_interface[012] macros the sample above implements two xpcom interfaces in addition to nsisupports. the ns_impl_query_interface2 macro c...
Memory reporting
the size of p by asking the heap allocator how big it is (via moz_malloc_usable_size). all this is probably not what you'd expect, but the above functions have the following crucial features. they let you measure the mystring object itself or not as necessary. this is important because sometimes an object might be embedded in another object that is measured separately. and the names make it clear exactly what is being measured. on platforms that allow it, they count the actual memory in use, including "slop" bytes caused by the heap allocator rounding up request sizes (a.k.a. internal fragmentation). if slop bytes aren't measured they'll end up in about:memory's heap-unclassified entry, which is bad. the size is not computed analytically. for example, sizeof doesn't appear anywhere. thi...
...able. nsthashtable's functions take an extra argument which is a pointer to a function that measures the memory usage of any structures pointed to by entries in the hash table. sometimes you may need variations on the above forms. for example, if you have a function that just measures one member mfoo of an object, it might be called sizeoffoo. try to make the names descriptive enough that it's clear what's being measured. sometimes you might want to split the measurements of an object into two or more numbers, e.g. because you want to show them separately in about:memory. in this case it's often clearer to increment the numbers rather than assigning to them, especially if you're measuring multiple entities and summing their measurements. for example: void foobar::addsizeofexcludingthis(n...
...eout += ...; } alternatively, you could create a struct: struct foobarsizes { size_t mfoo; size_t mbar; foobarsizes() { mozilla::podzero(this); } } void foobar::addsizeofexcludingthis(nsmallocsizeoffun amallocsizeof, foobarsizes* asizes) const { asizes->mfoo += ...; asizes->mbar += ...; } note the add prefix that makes this incrementing behaviour clear. obviously, if you increment you have to zero the values at some point. when using a struct, its constructor is the obvious place for this. you could even put the nsmallocsizeoffun in foobarsizes to reduce the number of arguments. sometimes it's difficult and/or not worth measuring every member of an object of in a foo::sizeofexcludingthis method. this is ok, but it's worth adding a comment...
Power profiling overview
and power is measured in watts, which is equivalent to joules per second. although power is an instantaneous concept, in practice measurements of it are determined in a non-instantaneous fashion, i.e. by dividing an energy amount by a non-infinitesimal time period. strictly speaking, such a computation gives the average power but this is often referred to as just the power when context makes it clear. in the context of computing, a fully-charged mobile device battery (as found in a laptop or smartphone) holds a certain amount of energy, and the speed at which that stored energy is depleted depends on the power consumption of the mobile device. that in turn depends on the software running on the device. web browsers are popular applications and can be power-intensive, and therefore can signif...
...easurements and estimates, which is vital for gaining insight into how a program can reduce power consumption. most profiling tools provide at least some proxy measurements. hybrid proxy measurements these are combinations of proxy measurements. the combinations are semi-arbitrary, they amplify the unreliability of proxy measurements, and unlike non-hybrid proxy measurements, they don't have a clear physical meaning. avoid them. the most notable example of a hybrid proxy measurement is the "energy impact" used by os x's activity monitor. ways to user power-related measurements low-context measurements most power-related measurements are global or per-process. such low-context measurements are typically good for understand if power consumption is good or bad, but in the latter case they o...
...ticularly useful if the workloads only vary slightly. for example, it can be useful to gradually remove elements from a web page and see how the power-related measurements change. even just switching a tab from the foreground to the background can make a difference. high-context measurements a few power-related measurements can be obtained in a high-context fashion, e.g. with stack traces that clearly pinpoint specific parts of the code as being responsible. standard performance profiling tools that measure cpu usage or proxies of cpu usage (such as instruction counts) typically provide high-context measurements. this is useful because high cpu usage typically causes high power consumption. some tools can provide high-context wakeup measurements: dtrace (on mac) and perf (on linux.) sou...
Index
to set a module as the default provider for mechanisms, use the -default command with a colon-separated list of mechanisms. the available mechanisms depend on the module; nss supplies almost all common mechanisms. for example: modutil -default "nss internal pkcs #11 module" -dbdir -mechanisms rsa:dsa:rc2 using database directory c:\databases... successfully changed defaults. clearing the default provider has the same format: modutil -undefault "nss internal pkcs #11 module" -dbdir -mechanisms md2:md5 enabling and disabling modules and slots modules, and specific slots on modules, can be selectively enabled or disabled using modutil. both commands have the same format: modutil -enable|-disable modulename [-slot slotname] for example: modutil -enable "ns...
... the -c# option is not used with the -j option, the default compression value is 6. note that versions 1.1 and later of netscape signing tool correctly recognizes the codebase attribute, allows paths to be expressed for the class and src attributes instead of filenames only, processes link tags and parses html correctly, and offers clearer error messages. -l lists the certificates in your database. an asterisk appears to the left of the nickname for any certificate that can be used to sign objects with signtool. --leavearc retains the temporary .arc (archive) directories that the -j option creates. these directories are automatically erased by default. re...
...0/md5 } session-id = { } challenge = { 0x0355 0xe6e4 0x9979 0xc7d7 0x2c86 0x7896 0x5db 0xcfe9 } } ] <additional records in same formats> server socket closed. usage tips when ssl restarts a previous session, it makes use of cached information to do a partial handshake. if you wish to capture a full ssl handshake, restart the browser to clear the session id cache. if you run the tool on a machine other than the ssl server to which you are trying to connect, the browser will complain that the host name you are trying to connect to is different from the certificate. if you are using the default badcert callback, you can still connect through a dialog. if you are not using the default badcert callback, the one you supp...
NSS API Guidelines
m: the boxes in the gray section, towards the center, are exported only through pkcs #11. pkcs #11 is only exported through the wrappers. the areas which need the most work (both here and throughout the code) is: the relationship of the certificate library with just about every other component (most noticeably pkcs #12, pkcs #7, and pkcs #11) splitting low key and high key components more clearly the crypto wrappers (pkcs #11 wrappers) and high key pkcs #12 and pkcs #5 libraries nss compiles into the libraries described below. the layer indicates the main layer, seen in the previous diagram, in which the library operates. the directory is the location of the library code in the nss source tree. the public headers is a list of header files that contain types, and functions, that...
...l, use another mechanism. errors, though not integers, are done as external constants, instead of preprocessor definitions. this is so any additional error doesn't trigger the entire tree to rebuild. likewise, the external references to errors are made in the prototypes files, with the functions which can return them. error stacks are thread-private. ...
...ich can return them. error stacks are thread-private. the usual semantic is that public routines clear the stack first, private routines don't. usually, every public routine has a private counterpart, and the implementation of the public routine looks like this: nssimplement rv * nsstype_method ( nsstype *t, nssfoo *arg1, nssbar *arg2 ) { nss_clearerrorstack(); #ifdef debug if( !nssfoo_verifypointer(arg1) ) return (rv *)null; if( !nssbar_verifypointer(arg2) ) return (rv *)null; #endif /* debug */ return nsstype_method(t, arg1, arg2); } aside from error cases, all documented entry points should check pointers in a debug, wherever possible. pointers to user-supplied buffers, and template...
JSAPI User Guide
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 to the error reporter and the pending exception is cleared. the basic consequence is that top-level application code can just set an error reporter and start calling jsapi functions. it never has to explicitly handle uncaught exceptions; the error reporter is automatically called. an application can disable automatic uncaught-exception handling using the jsoption_dont_report_uncaught option, but it must then deal with uncaught exceptions explicitly by...
...and start calling jsapi functions. it never has to explicitly handle uncaught exceptions; the error reporter is automatically called. an application can disable automatic uncaught-exception handling using the jsoption_dont_report_uncaught option, but it must then deal with uncaught exceptions explicitly by calling js_isexceptionpending, js_getpendingexception, js_reportpendingexception, and/or js_clearpendingexception whenever a jsapi function returns false or nullptr. uncatchable errors another way for a jsnative callback to report an error is like this: if (!p) { js_reportoutofmemory(cx); return false; } this does something subtly different from what js_reporterror does. most errors, including those raised by js_reporterror, are represented as javascript exceptio...
...s the jsapi is concerned. (of course, if the error is that the system is out of memory, that problem remains to be dealt with.) here is some example code that throws an uncatchable error. /* call the error reporter, if any. this part is optional. */ js_reporterror(cx, "the server room is on fire!"); js_reportpendingexception(cx); /* make sure the error is uncatchable. */ js_clearpendingexception(cx); return false; more sample code the following examples illustrate how to achieve a few different effects using the jsapi. note that the most important example is in the "a minimal example" section above. more jsapi code samples appear in the jsapi phrasebook. defining objects and properties /* statically initialize a class to make "one-off" objects. */ jsclass my_cla...
JS_IsExceptionPending
determine whether an exception is pending in the js engine. syntax bool js_isexceptionpending(jscontext *cx); name type description cx jscontext * pointer to a js context to check for pending exceptions. description js_isexceptionpending returns true if an exception has been thrown in the context cx and the exception has not yet been caught or cleared. ...
...ion js_isexceptionpending returns true if an exception has been thrown in the context cx and the exception has not yet been caught or cleared. otherwise, it returns false this can be used from jsnative functions which call js code to determine if the called js code threw an exception or not. example /* jsapi */ bool pending; js::rootedvalue exception(cx); /* if an exception is pending, save and clear it. */ pending = js_isexceptionpending(cx); if (pending) { if (!js_getpendingexception(cx, &exception)) return false; js_clearpendingexception(cx); } /* ... code that might throw js exception ... */ if (js_isexceptionpending(cx)) { /* ... react to exception thrown in this block ... */ js_clearpendingexception(cx); } /* restore the original exception. */ if (pending) {...
...dingexception(cx); } /* ... code that might throw js exception ... */ if (js_isexceptionpending(cx)) { /* ... react to exception thrown in this block ... */ js_clearpendingexception(cx); } /* restore the original exception. ...
Animated PNG graphics
Mozilla › Tech › APNG
fer should be changed at the end of the delay (before rendering the next frame). valid values for dispose_op are: value constant description 0 apng_dispose_op_none no disposal is done on this frame before rendering the next; the contents of the output buffer are left as is. 1 apng_dispose_op_background the frame's region of the output buffer is to be cleared to fully transparent black before rendering the next frame. 2 apng_dispose_op_previous the frame's region of the output buffer is to be reverted to the previous contents before rendering the next frame. if the first 'fctl' chunk uses a dispose_op of apng_dispose_op_previous it should be treated as apng_dispose_op_background. blend_op<code> specifies whether the frame is t...
... apng_blend_op_over the frame should be composited onto the output buffer based on its alpha, using a simple over operation as described in the alpha channel processing section of the extensions to the png specification, version 1.2.0. note that the second variation of the sample code is applicable. note that for the first frame the two blend modes are functionally equivalent due to the clearing of the output buffer at the beginning of each play. the 'fctl' chunk corresponding to the default image, if it exists, has these restrictions: the x_offset and y_offset fields must be 0. the width and height fields must equal the corresponding fields from the 'ihdr' chunk. as noted earlier, the output buffer must be completely initialized to fully transparent black at the beginning of e...
...ists, has these restrictions: the x_offset and y_offset fields must be 0. the width and height fields must equal the corresponding fields from the 'ihdr' chunk. as noted earlier, the output buffer must be completely initialized to fully transparent black at the beginning of each play. this is to ensure that each play of the animation will be identical. decoders are free to avoid an explicit clear step as long as the result is guaranteed to be identical. for example, if the default image is included in the animation, and uses a blend_op of apng_blend_op_source, clearing is not necessary because the entire output buffer will be overwritten. 'fdat': the frame data chunk the 'fdat' chunk has the same purpose as an 'idat' chunk. it has the same structure as an 'idat' chunk, except preceded b...
Places Developer Guide
is the umbrella term for a set of apis for managing browsing history and uri metadata first introduced in firefox 3. it encompasses history, bookmarks, tags, favicons, and annotations. there are two models of identity in the system: uris, and unique integer identifiers for items in the bookmark system. some of the apis are uri-centric, some use item ids. the api signature and context usually make clear which is required. bookmarks the toolkit bookmarks service is nsinavbookmarksservice: var bookmarks = cc["@mozilla.org/browser/nav-bookmarks-service;1"] .getservice(ci.nsinavbookmarksservice); this service provides methods for adding, editing and deleting items in the bookmarks collection. types in the bookmark system there are the four types of items in the bookmarks system, and...
...var history = cc["@mozilla.org/browser/nav-history-service;1"]. getservice(ci.nsinavhistoryservice); let observer = { onbeginupdatebatch: function() { }, onendupdatebatch: function() { }, onvisit: function(auri, avisitid, atime, asessionid, areferringid, atransitiontype) { }, ontitlechanged: function(auri, apagetitle) { }, ondeleteuri: function(auri) { }, on...
...ed. var history = cc["@mozilla.org/browser/nav-history-service;1"]. ...
RefPtr
40 is on file to enforce this rule but hasn't yet been fixed. while refptr should not generally be used to hold a pointer to an xpcom interface, this is flexible. there are no technical problems with doing so, and in some cases it may be necessary (see bug 756640 comment 1). for example, we have template classes such as owningnullptr that can contain a refptr to an xpcom interface. ...
...r to an xpcom interface, this is flexible. there are no technical problems with doing so, and in some cases it may be necessary (see bug 756640 comment 1). for example, we have template classes such as owningnullptr that can contain a refptr to an xpcom interface. xxx it's not clear that the details in the following paragraph are correct. it was derived from an old #developers discussion. ...
...what goes wrong at runtime - uaf? memory leak? qi failure and null-deref crashes?. note: in the above example, "nscomptr<nsfoo>" might compile and work ok (it won't if your xpcom class multiply-inherits nsisupports). but this is considered bad form, and may soon be made a compile-time error. ...
nsIFaviconService
ce.setandloadfaviconforpage(pageuri, faviconuri, false); setfavicondata() obsolete since gecko 22.0 (firefox 22.0 / thunderbird 22.0 / seamonkey 2.19) note: this method was removed in gecko 22.0. you should use the new async api moziasyncfavicons.replacefavicondata() instead. this method stores the data of a given favicon. you must specify the mime type unless you're clearing the data. you can set the data even if you haven't called setfaviconurlforpage() yet. it will be stored but will not be associated with any page. however, any favicons not associated with a visited web page, bookmark, or "place:" uri will be expired when history cleanup is done. this might be done at any time on a timer, so you should not let the message loop run between calls or your icon may...
...ype, in prtime aexpiration ); parameters afaviconuri uri of the favicon whose data is being set. adata binary contents of the favicon to save. adatalen optional from gecko 2.0 length of binary data. amimetype mime type of the data to store. this is important so that we know what to report when the favicon is used. you should always set this param unless you are clearing an icon. aexpiration time in microseconds since the epoch when this favicon expires. until this time, we won't try to load it again. exceptions thrown ns_error_failure thrown if the favicon is overbloated and won't be saved to the db. setfavicondatafromdataurl() obsolete since gecko 22.0 (firefox 22.0 / thunderbird 22.0 / seamonkey 2.19) note: thi...
... a favicon with the given uri. you needn't have any specified data at this point. an entry linking the favicon with the page will be create with no data. you can populate it later with setfavicondata(). however, any favicons not associated with a visited web page, a bookmark, or a "place:" uri will be expired when history cleanup is done * (typically at app shutdown, but also possibly if the user clears their * cache or history). this will send out history notifications if the new favicon has any data. this means that you should try to set data first if you have it, otherwise the page might not get a notification sent for it since data setting does not send notifications. void setfaviconurlforpage( in nsiuri apageuri, in nsiuri afaviconuri ); parameters apageuri uri of the page wh...
nsIFocusManager
rticle. ...
... 5 move focus to the first focusable element. movefocus_last 6 move focus to the last focusable element. movefocus_root 7 move focus to the root element in the document. movefocus_caret 8 move focus to a link at the position of the caret. this is a special value used to focus links as the caret moves over them in caret browsing mode. methods clearfocus() clears the focused element within awindow. if the current focusedwindow is a descendant of awindow, sets the current focusedwindow to awindow. void clearfocus( in nsidomwindow awindow ); parameters awindow exceptions thrown ns_error_invalid_arg if awindow is null. native code only!contentremoved obsolete since gecko 2.0 (firefox 4 / thunderbird 3.3 / seamonkey 2.
...lement. if no element is focused, focus the first focusable element within the document (or the last focusable element if atype is movefocus_end). this method is equivalent to setting the focusedelement to the new element. specifying astartelement and using movefocus_last is not currently implemented. if no element is found, and atype is either movefocus_root or movefocus_caret, then the focus is cleared. if atype is any other value, the focus is not changed. nsidomelement movefocus( in nsidomwindow awindow, in nsidomelement astartelement, in unsigned long atype, in unsigned long aflags ); parameters awindow astartelement atype aflags return value the element that was focused. setfocus() changes the focused element reference within the window c...
nsINavHistoryObserver
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?). ...
...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 onendupdatebatch() is called. void onbeginupdatebatch(); parameters none. onclearhistory() called just prior to all of history being cleared. void onclearhistory(); parameters none. ondeleteuri() the specified page and all its visits has been deleted. delete notifications are not quite 100% accurate. batch delete operations take place in two steps; the notifications come first, followed by a bulk delete. if an error occurs in between these two steps (for example, an out of me...
...ete. if an error occurs in between these two steps (for example, an out of memory error), then you may get a notification even though the page doesn't wind up getting deleted. note: the page does not necessarily have to have ever existed for this function to be called. notes the removepagesbyhost() and removepagesbytimeframe() functions call beginupdatebatch() and endupdatebatch() rather than onclearhistory() or ondeleteuri(). void ondeleteuri( in nsiuri auri, in acstring aguid ); parameters auri the uri of the page that was deleted. aguid the unique id associated with the page. ondeletevisits() called when some visits of an history entry are expired. note: when all visits for a page are expired and also the full page entry is expired, you will only get an ondeleteur...
nsISHEntry
d 6.0 / seamonkey 2.3) implemented by: @mozilla.org/browser/session-history-entry;1. ...
...are restored as children of the parent docshell, in this order, when the parent docshell restores a saved presentation. append a child shell to the end of our list. void addchildshell( in nsidocshelltreeitem shell ); parameters shell childshellat() nsidocshelltreeitem childshellat( in long index ); parameters index the child shell at index; null if index is out of bounds. return value clearchildshells() clear the child shell list. void clearchildshells(); parameters none. clone() nsishentry clone(); parameters none. return value native code only!create additional ways to create an entry. void create( in nsiuri uri, in astring title, in nsiinputstream inputstream, in nsilayouthistorystate layouthistorystate, in nsisupports cachekey, in acstring contenttype, in nsisup...
...uedocidentifier(); parameters none. seturi() uri for the document. void seturi( in nsiuri auri ); parameters auri native code only!setviewerbounds void setviewerbounds( in nsintrect bounds ); parameters bounds syncpresentationstate() ensure that the cached presentation members are self-consistent. if either contentviewer or windowstate are null, then all of the following members are cleared/reset: contentviewer, sticky, windowstate, viewerbounds, childshells, refreshurilist. void syncpresentationstate(); parameters none. example see nssessionstore.js for a real example. ...
nsITreeBoxObject
view nsitreeview the view that backs the tree and that supplies it with its data. it is dynamically settable, either using a view attribute on the tree tag or by setting this attribute to a new value. focused boolean whe...
...ng rowcountchanged(rowindex+1, -1); beginupdatebatch() notify the tree that the view is about to perform a batch update, that is, add, remove or invalidate several rows at once. this must be followed by calling endupdatebatch(), otherwise the tree will get out of sync. ...
...a batch update, that is, add, remove or invalidate several rows at once. this must be followed by calling endupdatebatch(), otherwise the tree will get out of sync. void beginupdatebatch(); endupdatebatch() notify the tree that the view has completed a batch update. ...
nsIXSLTProcessor
/xslt/public/nsixsltprocessor.idlscriptable xslt processor inherits from: nsisupports last changed in gecko 1.7 implemented by: @mozilla.org/document-transformer;1?type=xslt. ...
...getparameter() gets a parameter if previously set by setparameter(). returns null otherwise. nsivariant getparameter( in domstring namespaceuri, in domstring localname ); parameters ...
...getparameter() gets a parameter if previously set by setparameter(). returns null otherwise. ...
Debugger.Script - Firefox Developer Tools
ment, intra-thread calls: the call takes place in the same thread that hit the breakpoint, and in the compartment containing the handler function (typically the debugger’s compartment). the new breakpoint belongs to the debugger instance to which this script belongs. disabling the debugger instance disables this breakpoint; and removing a global from the debugger instance’s set of debuggees clears all the breakpoints belonging to that debugger instance in that global’s scripts. getbreakpoints([offset]) if the instance refers to a jsscript, return an array containing the handler objects for all the breakpoints set atoffset in this script. ifoffset is omitted, return the handlers of all breakpoints set anywhere in this script. ifoffset is present, but not a valid offset in this scri...
... getbreakpoints([offset]) if the instance refers to a jsscript, return an array containing the handler objects for all the breakpoints set atoffset in this script. ifoffset is omitted, return the handlers of all breakpoints set anywhere in this script. ifoffset is present, but not a valid offset in this script, throw an error. if the instance refers to webassembly code, throw a typeerror. clearbreakpoint(handler, [offset]) if the instance refers to a jsscript, remove all breakpoints set in this debugger instance that usehandler as their handler. ifoffset is given, remove only those breakpoints set atoffset that usehandler; ifoffset is not a valid offset in this script, throw an error. note that, if breakpoints using other handler objects are set at the same location(s) ashandler, t...
...set]) if the instance refers to a jsscript, remove all breakpoints set in this debugger instance that usehandler as their handler. ifoffset is given, remove only those breakpoints set atoffset that usehandler; ifoffset is not a valid offset in this script, throw an error. note that, if breakpoints using other handler objects are set at the same location(s) ashandler, they remain in place. clearallbreakpoints([offset]) if the instance refers to a jsscript, remove all breakpoints set in this script. ifoffset is present, remove all breakpoints set at that offset in this script; ifoffset is not a valid bytecode offset in this script, throw an error. isincatchscope([offset]) if the instance refers to a jsscript, this is true if this offset falls within the scope of a try block, and fals...
The JavaScript input interpreter - Firefox Developer Tools
highlighting is not visible in your browser if accessibility features have been enabled. execution history the interpreter remembers expressions you've typed. to move back and forward through your history: in single-line mode, use the up and down arrows. in multi-line mode, use the ⋀ and ⋁ icons in the editing panel's toolbar. the expression history is persisted across sessions. to clear the history, use the clearhistory() helper function. you can initiate a reverse search through the expression history, much like you can in bash on linux and mac or powershell on windows. on windows and linux press f9. on mac press ctrl+r (note: not cmd+r!) to initiate the reverse search. enter the text you want to search for in the input box at the bottom of the console. start typing part of...
...e of result to return; it can be an xpathresult constant, or a corresponding string: "number", "string", "bool", "node", or "nodes"; if not provided, any_type is used. keys() given an object, returns a list of the keys (or property names) on that object. this is a shortcut for object.keys. values() given an object, returns a list of the values on that object; serves as a companion to keys(). clear() clears the console output area. inspect() given an object, opens the object inspector for that object. pprint() obsolete since gecko 74 formats the specified value in a readable way; this is useful for dumping the contents of objects and arrays. help()deprecated since gecko 62 :help displays help text. actually, in a delightful example of recursion, it will bring you to this page. cd()...
...locate the iframe element the iframe element itself the content window inside the iframe see working with iframes. copy() new in firefox 38. copy the argument to the clipboard. if the argument is a string, it's copied as-is. if the argument is a dom node, its outerhtml is copied. otherwise, json.stringify will be called on the argument, and the result will be copied to the clipboard. clearhistory() new in firefox 39. just like a normal command line, the console command line remembers the commands you've typed. use this function to clear the console's command history. :screenshot new in firefox 62. create a screenshot of the current page with the supplied filename. if you don't supply a filename, the image file will be named: screen shot yyy-mm-dd at hh.mm.ss.png the comman...
Web Console remoting - Firefox Developer Tools
, "from": "conn0.console34" } you can also use the webconsoleclient.getpreferences(prefs, onresponse). the prefs argument is an array of preferences you want to get their values for, by name. private browsing the browser console can be used while the user has private windows open. each page error, console api message and network request is annotated with a private flag. private messages are cleared whenever the last private window is closed. the console actor provides the lastprivatecontextexited notification: { "from": "conn0.console19", "type": "lastprivatecontextexited" } this notification is sent only when your client is attached to the global console actor, it does not make sense for tab console actors. this notification has been introduced in firefox 24. send http request...
... network logging the networkevent packet whenever a new network request starts being logged the networkevent packet is sent: { "from": "conn0.console10", "type": "networkevent", "eventactor": { "actor": "conn0.netevent14", "starteddate...
...tocomplete", "text": "d", "cursor": 1 } the response packet: { "from": "conn0.console9", "matches": [ "decodeuri", "decodeuricomponent", "defaultstatus", "devicepixelratio", "disableexternalcapture", "dispatchevent", "domyxhr", "document", "dump" ], "matchprop": "d" } there's also the clearmessagescache request packet that has no response. this clears the console api calls cache and should clear the page errors cache - see bug 717611. network logging the networkevent packet whenever a new network request starts being logged the networkevent packet is sent: { "from": "conn0.console10", "type": "networkevent", "eventactor": { "actor": "conn0.netevent14", "starteddatetime": "2012-09-17t19:50:03.699z", "url": "http://localho...
CanvasRenderingContext2D - Web APIs
tx.linewidth = 10; // wall ctx.strokerect(75, 140, 150, 110); // door ctx.fillrect(130, 190, 40, 60); // roof ctx.beginpath(); ctx.moveto(50, 140); ctx.lineto(150, 60); ctx.lineto(250, 140); ctx.closepath(); ctx.stroke(); the resulting drawing looks like this: reference drawing rectangles there are three methods that immediately draw rectangles to the canvas. canvasrenderingcontext2d.clearrect() sets all pixels in the rectangle defined by starting point (x, y) and size (width, height) to transparent black, erasing any previously drawn content. canvasrenderingcontext2d.fillrect() draws a filled rectangle at (x, y) position whose size is determined by width and height. canvasrenderingcontext2d.strokerect() paints a rectangle which has a starting point at (x, y) and has a w width...
...ack' saved by save(). canvasrenderingcontext2d.canvas a read-only back-reference to the htmlcanvaselement. might be null if it is not associated with a <canvas> element. hit regions canvasrenderingcontext2d.addhitregion() adds a hit region to the canvas. canvasrenderingcontext2d.removehitregion() removes the hit region with the specified id from the canvas. ...
... canvasrenderingcontext2d.drawimagefromrect() this is redundant with an equivalent overload of drawimage. canvasrenderingcontext2d.setalpha() use canvasrenderingcontext2d.globalalpha instead. ...
Applying styles and colors - Web APIs
e lines, and whose height is decreasing between corners from left to right because they connect with growing angles; with intermediate values, the corners on the left side will only join with a bevel near the blue lines, and the corners on the right side with a miter extension (also with a decreasing height). ...
...height is decreasing between corners from left to right because they connect with growing angles; with intermediate values, the corners on the left side will only join with a bevel near the blue lines, and the corners on the right side with a miter extension (also with a decreasing height). ...
...tion tools of computer graphics programs. it helps the user to distinguish the selection border from the image background by animating the border. in a later part of this tutorial, you can learn how to do this and other basic animations. <canvas id="canvas" width="110" height="110"></canvas> var ctx = document.getelementbyid('canvas').getcontext('2d'); var offset = 0; function draw() { ctx.clearrect(0, 0, canvas.width, canvas.height); ctx.setlinedash([4, 2]); ctx.linedashoffset = -offset; ctx.strokerect(10, 10, 100, 100); } function march() { offset++; if (offset > 16) { offset = 0; } draw(); settimeout(march, 20); } march(); screenshotlive sample gradients just like any normal drawing program, we can fill and stroke shapes using linear and radial gradients. we c...
Compositing example - Web APIs
op; dl.appendchild(dt); var dd = document.createelement("dd"); var p = document.createelement("p"); p.textcontent = gcotext.pop(); dd.appendchild(p); var canvastodrawon = createcanvas(); var canvastodrawfrom = createcanvas(); var canvastodrawresult = createcanvas(); var ctx = canvastodrawresult.getcontext('2d'); ctx.clearrect(0, 0, width, height) ctx.save(); ctx.drawimage(canvas1, 0, 0, width/2, height/2); ctx.globalcompositeoperation = pop; ctx.drawimage(canvas2, 0, 0, width/2, height/2); ctx.globalcompositeoperation = "source-over"; ctx.fillstyle = "rgba(0,0,0,0.8)"; ctx.fillrect(0, height/2 - 20, width/2, 20); ctx.fillstyle = "#fff"; ctx.fo...
... ctx.drawimage(canvas2, 0, 0, width/2, height/2); ctx.globalcompositeoperation = "source-over"; ctx.fillstyle = "rgba(0,0,0,0.8)"; ctx.fillrect(0, height/2 - 20, width/2, 20); ctx.fillstyle = "#fff"; ctx.font = "14px arial"; ctx.filltext(pop, 5, height/2 - 5); ctx.restore(); var ctx = canvastodrawon.getcontext('2d'); ctx.clearrect(0, 0, width, height) ctx.save(); ctx.drawimage(canvas1, 0, 0, width/2, height/2); ctx.fillstyle = "rgba(0,0,0,0.8)"; ctx.fillrect(0, height/2 - 20, width/2, 20); ctx.fillstyle = "#fff"; ctx.font = "14px arial"; ctx.filltext('existing content', 5, height/2 - 5); ctx.restore(); var ctx = canvastodrawfrom.getcontext('2d'); ...
...idth, height) ctx.save(); ctx.drawimage(canvas1, 0, 0, width/2, height/2); ctx.fillstyle = "rgba(0,0,0,0.8)"; ctx.fillrect(0, height/2 - 20, width/2, 20); ctx.fillstyle = "#fff"; ctx.font = "14px arial"; ctx.filltext('existing content', 5, height/2 - 5); ctx.restore(); var ctx = canvastodrawfrom.getcontext('2d'); ctx.clearrect(0, 0, width, height) ctx.save(); ctx.drawimage(canvas2, 0, 0, width/2, height/2); ctx.fillstyle = "rgba(0,0,0,0.8)"; ctx.fillrect(0, height/2 - 20, width/2, 20); ctx.fillstyle = "#fff"; ctx.font = "14px arial"; ctx.filltext('new content', 5, height/2 - 5); ctx.restore(); dd.appendchild(canvastodrawon); dd.appendc...
DataTransfer.setData() - Web APIs
same type. example data types are text/plain and text/uri-list. syntax void datatransfer.setdata(format, data); arguments format a domstring representing the type of the drag data to add to the drag object. data a domstring representing the data to add to the drag object. ...
...a); arguments format a domstring representing the type of the drag data to add to the drag object. data a domstring representing the data to add to the drag object. return value void example this example shows the use of the datatransfer object's getdata(), setdata() and cleardata() methods. ...
...event target's id for the data ev.datatransfer.setdata("text/plain", ev.target.id); } function dragover_handler(ev) { console.log("dragover"); ev.preventdefault(); } function drop_handler(ev) { console.log("drop"); ev.preventdefault(); // get the data, which is the id of the drop target var data = ev.datatransfer.getdata("text"); ev.target.appendchild(document.getelementbyid(data)); // clear the drag data cache (for all formats/types) ev.datatransfer.cleardata(); } </script> <body> <h1>examples of <code>datatransfer</code>: <code>setdata()</code>, <code>getdata()</code>, <code>cleardata()</code></h1> <div> <p id="source" ondragstart="dragstart_handler(event);" draggable="true"> select this element, drag it to the drop zone and then release the selection to move the element.
DataTransfer - Web APIs
nt, and is true if the user canceled the drag operation by pressing escape. it will be false in all other cases, including if the drag failed for any other reason, for instance due to a drop over an invalid location. deprecated properties datatransfer.mozitemcount read only gives the number of items in the drag operation. removed in firefox 71. methods standard methods datatransfer.cleardata() remove the data associated with a given type. the type argument is optional. if the type is empty or not specified, the data associated with all types is removed. if data for the specified type does not exist, or the data transfer contains no data, this method will have no effect. datatransfer.getdata() retrieves the data for a given type, or an empty string if data for that type does no...
...l be the new format. if data for the type already exists, the existing data is replaced in the same position. datatransfer.setdragimage() set the image to be used for dragging if a custom one is desired. gecko methods note: all of the methods in this section are gecko-specific. datatransfer.addelement() sets the drag source to the given element. deprecated methods datatransfer.mozcleardataat() removes the data associated with the given format for an item at the specified index. the index is in the range from zero to the number of items minus one. removed in firefox 71. datatransfer.mozgetdataat() retrieves the data associated with the given format for an item at the specified index, or null if it does not exist. the index should be in the range from zero to the number of...
...listed in this document has its own reference page and each reference page either directly includes an example of the interface or has a link to an example. specifications specification status comment html living standardthe definition of 'datatransfer' in that specification. living standard mozcursor, mozitemcount, mozsourcenode, mozusercancelled, addelement(), mozcleardataat(), mozgetdataat(), mozsetdataat() and moztypesat are gecko specific. html 5.1the definition of 'datatransfer' in that specification. recommendation not included in w3c html5 recommendation ...
Event.eventPhase - Web APIs
Web › API › Event › eventPhase
eckbox" id="chcapture" /> <label for="chcapture">use capturing</label> <div id="d1">d1 <div id="d2">d2 <div id="d3">d3 <div id="d4">d4</div> </div> </div> </div> <div id="divinfo"></div> css div { margin: 20px; padding: 4px; border: thin black solid; } #divinfo { margin: 18px; padding: 8px; background-color:white; font-size:80%; } javascript let clear = false, divinfo = null, divs = null, usecapture = false; window.onload = function () { divinfo = document.getelementbyid('divinfo') divs = document.getelementsbytagname('div') chcapture = document.getelementbyid('chcapture') chcapture.onclick = function () { removelisteners() addlisteners() } clear() addlisteners() } function removelisteners() { for (let i =...
..."none" : e.eventphase == 1 ? "capturing" : e.eventphase == 2 ? "target" : e.eventphase == 3 ? "bubbling" : "error"; divinfo.innerhtml += e.curren...
...ction addlisteners() { for (let i = 0; i < divs.length; i++) { let d = divs[i] if (d.id != "divinfo") { if (chcapture.checked) { d.addeventlistener("click", ondivclick, true) } else { d.addeventlistener("click", ondivclick, false) d.onmousemove = function () { clear = true } } } } } function ondivclick(e) { if (clear) { clear() clear = false } if (e.eventphase == 2) e.currenttarget.style.backgroundcolor = 'red'; let level = e.eventphase == 0 ? "none" : e.eventphase == 1 ? "capturing" : e.eventphase == 2 ? "target" : e.eventphase == 3 ? "bubbling" : "error"; divinfo.innerhtml += e.currenttarget.id + "; eventphase: " + level + "<br/>"; } function clear() ...
MediaSession.setPositionState() - Web APIs
e browser. call this method on the navigator object's mediasession object. syntax navigator.mediasession.setpositionstate(statedict); parameters statedict optional an object conforming to the mediapositionstate dictionary, providing updated information about the playback position and speed of the document's ongoing media. if the object is empty, the existing playback state information is cleared. return value undefined. exceptions typeerror this error can occur in an array of circumstances: the specified mediapositionstate object's duration is missing, negative, or null. position is missing or null, or is either negative or greater than duration. the playbackrate is zero. example in this example, a player for a non-standard media file format, written in javasc...
..., uses setinterval() to establish a callback which fires once per second to refresh the position information by calling setpositionstate(). if the media is still playing when the interval is fired, setpositionstate() is called with an object that specifies the duration, playback rate, and position as reported by a mymedia object that describes the track being played. ...
...rack being played. if the media is not playing, clearinterval() is used to remove the interval handler. let positioninterval = window.setinterval(() => { if (mymedia.isplaying) { navigator.mediasession.setpositionstate({ duration: mymedia.trackdurationinseconds, playbackrate: mymedia.playbackrate, position: mymedia.trackplaypositioninseconds }); } else { window.clearinterval(positioninterval); } }, 1000); specifications specification status comment media session standardthe definition of 'mediasession.setpositionstate()' in that specification. draft initial definition. ...
Using the Notifications API - Web APIs
d versions of chrome didn't remove notifications automatically so you can do so after a settimeout() only for those legacy versions in order to not remove notifications from notification trays on other browsers. var n = new notification('my great song'); document.addeventlistener('visibilitychange', function() { if (document.visibilitystate === 'visible') { // the tab has become visible so clear the now-stale notification. n.close(); } }); note: this api shouldn't be used just to have the notification removed from the screen after a fixed delay (on modern browsers) since this method will also remove the notification from any notification tray, preventing users from interacting with it after it was initially shown. note: when you receive a "close" event, there is no guarantee ...
...) { var i = 0; // using an interval cause some browsers (including firefox) are blocking notifications if there are too much in a certain time. var interval = window.setinterval(function () { // thanks to the tag, we should only see the "hi! 9" notification var n = new notification("hi! " + i, {tag: 'somanynotification'}); if (i++ == 9) { window.clearinterval(interval); } }, 200); } // if the user hasn't told if he wants to be notified or not // note: because of chrome, we are not sure the permission property // is set, therefore it's unsafe to check for the "default" value. else if (window.notification && notification.permission !== "denied") { notification.requestpermission(function (status) { ...
... // using an interval cause some browsers (including firefox) are blocking notifications if there are too much in a certain time. ...
Performance - Web APIs
ers. performance.memory read only a non-standard extension added in chrome, this property provides an object with basic memory usage information. you should not use this non-standard api. performance.timeorigin read only returns the high resolution timestamp of the start time of the performance measurement. methods the performance interface doesn't inherit any methods. performance.clearmarks() removes the given mark from the browser's performance entry buffer. performance.clearmeasures() removes the given measure from the browser's performance entry buffer. performance.clearresourcetimings() removes all performance entries with a entrytype of "resource" from the browser's performance data buffer. performance.getentries() returns a list of performanceentry objects based on...
...ification. candidate recommendation changes getentries() interface. performance timelinethe definition of 'performance extensions' in that specification. recommendation defines getentries(), getentriesbytype() and getentriesbyname() methods. resource timing level 1the definition of 'performance extensions' in that specification. candidate recommendation defines clearresourcetimings() and setresourcetimingbuffersize() methods and the onresourcetimingbufferfull property. user timing level 2the definition of 'performance extensions' in that specification. working draft clarifies mark(), clearmark(), measure() and clearmeasure() methods. user timingthe definition of 'performance extensions' in that specification. recommendation defin...
...ings() and setresourcetimingbuffersize() methods and the onresourcetimingbufferfull property. user timing level 2the definition of 'performance extensions' in that specification. working draft clarifies mark(), clearmark(), measure() and clearmeasure() methods. user timingthe definition of 'performance extensions' in that specification. recommendation defines mark(), clearmark(), measure() and clearmeasure() methods. ...
Using the Resource Timing API - Web APIs
le.log("... transfersize[" + i + "] = not supported"); } } managing the resource buffer although the browser is required to support at least 150 resource timing performance entries in its resource timing buffer, some applications may use more resources than that limit. to help the developer manage the buffer size, resource timing defines two methods that extend the performance interface. ...
... that extend the performance interface. the clearresourcetimings() method removes all "resource" type performance entries from the browser's resource performance entry buffer. the setresourcetimingbuffersize() method sets the resource performance entry buffer size to the specified number of resource performance entries. the following example demonstrates the usage of these two methods. function clear_resource_timings() { if (performance === undefined) { console.log("= performance.clearresourcetimings(): peformance not supported"); return; } // check if performance.clearresourcetiming() is supported console.log ("= print performance.clearresourcetimings()"); var supported = typeof performance.clearresourcetimings == "function"; if (supported) { console.log("... performa...
...ource_timings() { if (performance === undefined) { console.log("= performance.clearresourcetimings(): peformance not supported"); return; } // check if performance.clearresourcetiming() is supported console.log ("= print performance.clearresourcetimings()"); var supported = typeof performance.clearresourcetimings == "function"; if (supported) { console.log("... performance.clearresourcetimings() = supported"); performance.clearresourcetimings(); } else { console.log("... performance.clearresourcetiming() = not supported"); return; } // getentries should now return zero var p = performance.getentriesbytype("resource"); if (p.length == 0) console.log("... performance data buffer cleared"); else console.log("... performance data buffer not cl...
SVGPathSegList - Web APIs
svg path segment list interface this interface defines a list of svgpathseg objects. ...
... normative document svg 1.1 (2nd edition) properties name type description numberofitemsread only unsigned long the number of items in the list. methods clear() void clears all existing current items from the list, with the result being an empty list. exceptions: a domexception with code no_modification_allowed_err is raised when the list cannot be modified. initialize(in svgpathseg newitem) ...
...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. ...
SVGPointList - Web APIs
svg point list interface the svgpointlist defines a list of svgpoint objects. an svgpointlist object can be designated as read only, which means that attempts to modify the object will result in an exception being thrown. ...
... properties name type description numberofitems unsigned long the number of items in the list. methods name & arguments return description clear() void clears all existing current items from the list, with the result being an empty list. exceptions: a domexception with code no_modification_allowed_err is raised when the list corresponds to a read only attribute or when the object itself is read only. initialize(in svgpoint 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. ...
Multi-touch interaction - Web APIs
// indicate the target received a move event. // ev.preventdefault(); if (logevents) log("touchmove", ev, false); // to avoid too much color flashing many touchmove events are started, // don't update the background if two touch points are active if (!(ev.touches.length == 2 && ev.targettouches.length == 2)) update_background(ev); // set the target element's border to dashed to give a clear visual // indication the element received a move event. ev.target.style.border = "dashed"; // check this event for 2-touch move/pinch/zoom gesture handle_pinch_zoom(ev); } touch end handler the touchend handler restores the event target's background color back to its original color. function end_handler(ev) { ev.preventdefault(); if (logevents) log(ev.type, ev, false); if (ev.targe...
... function end_handler(ev) { ev.preventdefault(); if (logevents) log(ev.type, ev, false); if (ev.targettouches.length == 0) { // restore background and border to original values ev.target.style.background = "white"; ev.target.style.border = "1px solid black"; } } application ui the application uses <div> elements for the touch areas and provides buttons to enable logging and clear the log. <div id="target1"> tap, hold or swipe me 1</div> <div id="target2"> tap, hold or swipe me 2</div> <div id="target3"> tap, hold or swipe me 3</div> <div id="target4"> tap, hold or swipe me 4</div> <!-- ui for logging/bebugging --> <button id="log" onclick="enablelog(event);">start/stop event logging</button> <button id="clearlog" onclick="clearlog(event);">clear the log</button> <p></p>...
...ame + ": touches = " + ev.touches.length + " ; targettouches = " + ev.targettouches.length + " ; changedtouches = " + ev.changedtouches.length; o.innerhtml += s + " "; if (printtargetids) { s = ""; for (var i=0; i < ev.targettouches.length; i++) { s += "... id = " + ev.targettouches[i].identifier + " "; } o.innerhtml += s; } } function clearlog(event) { var o = document.getelementsbytagname('output')[0]; o.innerhtml = ""; } related topics and resources pointer events ...
Vibration API - Web APIs
ber 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, an empty array, or an array containing all zeros will cancel any currently ongoing vibration pattern. ...
...empty array, or an array containing all zeros will cancel any currently ongoing vibration pattern. ...
...ly ongoing vibration pattern. ...
WebGLRenderingContext.getParameter() - Web APIs
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 ...
...t.compressed_srgb8_alpha8_astc_12x10_khr ext.compressed_rgba_astc_12x12_khr ext.compressed_srgb8_alpha8_astc_12x12_khr gl.cull_face glboolean gl.cull_face_mode glenum gl.front, gl.back or gl.front_and_back. see also cullface gl.current_program webglprogram or null see useprogram. ...
... gl.stencil_back_fail glenum gl.stencil_back_func glenum gl.stencil_back_pass_depth_fail glenum gl.stencil_back_pass_depth_pass glenum gl.stencil_back_ref glint gl.stencil_back_value_mask gluint gl.stencil_back_writemask gluint gl.stencil_bits glint gl.stencil_clear_value glint gl.stencil_fail glenum gl.stencil_func glenum gl.stencil_pass_depth_fail glenum gl.stencil_pass_depth_pass glenum gl.stencil_ref glint gl.stencil_test glboolean gl.stencil_value_mask gluint gl.stencil_writemask gluint gl.subpixel_bits glint...
Boilerplate 1 - Web APIs
tton. any additional non-trivial css and html will be displayed on the pages of specific examples. in following examples, we will use a javascript helper function, getrenderingcontext(), to initialize the webgl rendering context. by now, you should be able to understand what the function does. basically, it gets the webgl rendering context from the canvas element, initializes the drawing buffer, clears it black, and returns the initialized context. in case of error, it displays an error message and returns null. finally, all javascript code will run within an immediate function, which is a common javascript technique (see function). the function declaration and invocation will also be hidden. html <p>[ some descriptive text about the example. ]</p> <button>[ optional button element. ]</bu...
... « previousnext » ...
... « previousnext » ...
Canvas size and WebGL - Web APIs
the size of the first canvas is set to the styled element size, determined by css. ...
... css. this is done by assigning the width and height properties of the canvas to the values of the clientwidth and clientheight properties, respectively. in contrast, no such assignment is done for the second canvas. the internal width and height properties of the canvas remain at default values, which are different than the actual size of the canvas element in the browser window. the effect is clearly visible when using scissor() and clear() to draw a square in the center of the canvas, by specifying its position and size in pixels. in the first canvas, we get the desired result. in the second, the square has the wrong shape, size, and position. <p>compare the two canvases.</p> <canvas>your browser does not seem to support html5 canvas.</canvas> <canvas>your browser does not seem to s...
...as.getcontext("webgl") || canvas.getcontext("experimental-webgl"); if (!gl) { document.queryselector("p").innerhtml = "failed to get webgl context. " + "your browser or device may not support webgl."; return; } gl.viewport(0, 0, gl.drawingbufferwidth, gl.drawingbufferheight); gl.enable(gl.scissor_test); gl.scissor(30, 10, 60, 60); gl.clearcolor(1.0, 1.0, 0.0, 1.0); gl.clear(gl.color_buffer_bit); }); }, false); the source code of this example is also available on github. « previousnext » ...
XRView.eye - Web APIs
Web › API › XRView › eye
les this code, from the viewer pose's renderer, iterates over the pose's views and renders them. however, we have flags which, if true, indicate that a particular eye has been injured during gameplay. when rendering that eye, if the flag is true, that view is skipped instead of being rendered. ...
...wer pose's renderer, iterates over the pose's views and renders them. however, we have flags which, if true, indicate that a particular eye has been injured during gameplay. when rendering that eye, if the flag is true, that view is skipped instead of being rendered. ...
... iterates over the pose's views and renders them. however, we have flags which, if true, indicate that a particular eye has been injured during gameplay. when rendering that eye, if the flag is true, that view is skipped instead of being rendered. ...
XRWebGLLayer.getViewport() - Web APIs
's pose, it is rendered into the correct half of the framebuffer. ...
...correct half of the framebuffer. ...
...ebuffer. <<<--- add link to appropriate section in the cameras and views article --->>> function drawframe(time, frame) { let session = frame.session; let pose = frame.getviewerpose(mainreferencespace); if (pose) { let gllayer = session.renderstate.baselayer; gl.bindframebuffer(gl.framebuffer, gllayer.framebuffer); gl.clearcolor(0, 0, 0, 1.0); gl.cleardepth(1.0); gl.clear(gl.color_buffer_bit, gl.depth_color_bit); for (let view of pose.views) { let viewport = gllayer.getviewport(view); gl.viewport(viewport.x, viewport.y, viewport.width, viewport.height); /* render the scene now */ } } specifications specification status comment webxr device apithe definition of 'xrwebgllayer.getviewport()' in that specification. ...
ARIA Screen Reader Implementors Guide - Accessibility
ond hardware channel: if there are two channels for presentation (e.g. text to speech and a braille display), then two queues can be maintained to allow for parallel presentation. the channels could be user configured for presenting live regions based on role or politeness. ...
... time takes second precedence: prioritize items with the same politeness level according to when the event occurs (earlier events come first). present items of the same politeness level in the order of what occurred first. ...
... time takes second precedence: prioritize items with the same politeness level according to when 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. ...
outline-style - CSS: Cascading Style Sheets
style — typically a style [that] is either a user interface default for the platform, or perhaps a style that is richer than can be described in detail in css, e.g. a rounded edge outline with semi-translucent outer pixels that appears to glow. ...
.../* same result as "outline: auto" */ } /* to make the demo clearer */ * { outline-width: 10px; padding: 15px; } result setting outline style to dashed and dotted html <div> <div class="dotted"> <p class="dashed">outline demo</p> </div> </div> css .dotted { outline-style: dotted; /* same result as "outline: dotted" */ } .dashed { outline-style: dashed; } /* to make the demo clearer */ * { outline-width: 10px; padding: 15px; } result setting outline style to solid and double html <div> <div class="solid"> <p class="double">outline demo</p> </div> </div> css .solid { outline-style: solid; } .double { outline-style: double; } /* to make the demo clearer */ * { outline-width: 10px; padding: 15px; } result setting outline style to groove and ridge ...
...iv> css .solid { outline-style: solid; } .double { outline-style: double; } /* to make the demo clearer */ * { outline-width: 10px; padding: 15px; } result setting outline style to groove and ridge html <div> <div class="groove"> <p class="ridge">outline demo</p> </div> </div> css .groove { outline-style: groove; } .ridge { outline-style: ridge; } /* to make the demo clearer */ * { outline-width: 10px; padding: 15px; } result setting outline style to inset and outset html <div> <div class="inset"> <p class="outset">outline demo</p> </div> </div> css .inset { outline-style: inset; } .outset { outline-style: outset; } /* to make the demo clearer */ * { outline-width: 10px; padding: 15px; } result specifications specification stat...
<input type="time"> - HTML: Hypertext Markup Language
Web › HTML › Element › input › time
project, please clone https://github.com/mdn/interactive-examples and send us a pull request. appearance chrome and opera in chrome/opera the time control is simple, with slots to enter hours and minutes in 12 or 24-hour format depending on operating system locale, and up and down arrows to increment and decrement the currently selected component. in some versions, an "x" button is provided to clear the control's value. 12-hour 24-hour chrome 83 in chrome 83, the ui controls have been updated with a new look and feel. the new element is functionally identical to the old one, but has a similar ui to edge. 24-hour firefox firefox's time control is very similar to chrome's, except that it doesn't have the up and down arrows. it also uses a 12- or 24-hour format for inputting times, b...
... in chrome 83, the ui controls have been updated with a new look and feel. the new element is functionally identical to the old one, but has a similar ui to edge. 24-hour firefox firefox's time control is very similar to chrome's, except that it doesn't have the up and down arrows. it also uses a 12- or 24-hour format for inputting times, based on system locale. an "x" button is provided to clear the control's value. 12-hour 24-hour edge the edge time control is somewhat more elaborate, opening up an hour and minute picker with sliding reels. it, like chrome, uses a 12- or 24-hour format for inputting times, based on system locale: 12-hour 24-hour value a domstring representing a time, or empty. events change and input supported common attribute...
...he user agent may round to the nearest valid value, preferring numbers in the positive direction when there are two equally close options. for time inputs, the value of step is given in seconds, with a scaling factor of 1000 (since the underlying numeric value is in milliseconds). the default value of step is 60, indicating 60 seconds (or 1 minute, or 60,000 milliseconds). at this time, it's unclear what a value of any means for step when used with time inputs. this will be updated as soon as that information is determined. using time inputs although among the date and time input types time has the widest browser support, it is not yet approaching universal, so it is likely that you'll need to provide an alternative method for entering the date and time, so that safari users (and users of ...
Using the application cache - HTML: Hypertext Markup Language
the update halts. once all the files have been successfully retrieved, they are moved into the real offline cache automatically, and a cached event is sent to the applicationcache object. since the document has already been loaded into the browser from the cache, the updated document will not be rendered until the document is reloaded (either manually or programatically). storage location and clearing the offline cache in chrome you can clear the offline cache by selecting "clear browsing data..." in the preferences or by visiting chrome://appcache-internals/. safari has a similar "empty cache" setting in its preferences but a browser restart may also be required. in firefox, the offline cache data is stored separately from the firefox profile—next to the regular disk cache: windows ...
...o the regular disk cache: windows vista/7: c:\users\<username>\appdata\local\mozilla\firefox\profiles\<salt>.<profile name>\offlinecache mac/linux: /users/<username>/library/caches/firefox/profiles/<salt>.<profile name>/offlinecache in firefox the current status of the offline cache can be inspected on the about:cache page (under the "offline cache device" heading). the offline cache can be cleared for each site separately using the "remove..." button in tools -> options -> advanced -> network -> offline data. prior to firefox 11, neither tools -> clear recent history nor tools -> options -> advanced -> network -> offline data -> clear now cleared the offline cache. this has been fixed. on linux, you can find the setting at edit > preferences > advanced > network > offline web content a...
... application caches can also become obsolete. if an application's manifest file is removed from the server, the browser removes all application caches that use that manifest, and sends an "obsoleted" event to the applicationcache object. ...
Caching compiled WebAssembly modules - WebAssembly
s in the database, and retrieves previously cached modules from the database, saving you from having to download them again. note: the entire site's wasm cache (not just the given url) is versioned by the specified dbversion passed into the function. if the wasm module code is updated, or its url changes, you will need to update dbversion. any subsequent call to instantiatecachedurl() will then clear out the entire cache, allowing you to avoid using out-of-date modules. the function starts off by defining some necessary constants: function instantiatecachedurl(dbversion, url, importobject) { const dbname = 'wasm-cache'; const storename = 'wasm-cache'; setting up the database the first helper function contained inside instantiatecachedurl() — opendatabase() — creates an object sto...
...sing out-of-date modules. the function starts off by defining some necessary constants: function instantiatecachedurl(dbversion, url, importobject) { const dbname = 'wasm-cache'; const storename = 'wasm-cache'; setting up the database the first helper function contained inside instantiatecachedurl() — opendatabase() — creates an object store for storing wasm modules, and also handles clearing out the database if the dbversion is updated; it returns a promise resolving to the new database. function opendatabase() { return new promise((resolve, reject) => { var request = indexeddb.open(dbname, dbversion); request.onerror = reject.bind(null, 'error opening wasm cache database'); request.onsuccess = () => { resolve(request.result) }; request.onupgradeneed...
...{ return new promise((resolve, reject) => { var request = indexeddb.open(dbname, dbversion); request.onerror = reject.bind(null, 'error opening wasm cache database'); request.onsuccess = () => { resolve(request.result) }; request.onupgradeneeded = event => { var db = request.result; if (db.objectstorenames.contains(storename)) { console.log(`clearing out version ${event.oldversion} wasm cache`); db.deleteobjectstore(storename); } console.log(`creating version ${event.newversion} wasm cache`); db.createobjectstore(storename) }; }); } looking up modules in the database our next function — lookupindatabase() — provides a simple promise-based operation for looking up the given url in the ob...
Examples and demos from articles - Archive of obsolete content
] typewriter effect [html] the following example will delete and re-type simulating a typewriter all the text content of the nodelist which match a specified group of selectors. [article] fade in/out [html] sometimes a page uses dozens and dozens of animations. in such a condition is difficult and unnatural to keep track of all events started and then to stop them when appropriate through the cleartimeout() function. a possible approach to solve this problem is to nest all the informations needed by each animation to start, stop, etc. etc. 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. [art...
...ea 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. using setinterval within animations sometimes a page uses dozens and dozens of animations. in such a condition is difficult and unnatural to keep track of all events started and then to stop them when appropriate through the cleartimeout() function. a possible approach to solve this problem is to nest all the informations needed by each animation to start, stop, etc. etc. in different objects and then to create a constructor for such class of objects in order to standardize and simplify the instantiation of them. convert relative paths to absolute this example show how to translate relative paths to absolute paths. a sh...
JavaScript Debugger Service - Archive of obsolete content
ric createfilter function that acts as a jsdifilter factory. function createfilter(pattern, pass) { var jsdifilter = components.interfaces.jsdifilter; var filter = { globalobject: null, flags: pass ? (jsdifilter.flag_enabled | jsdifilter.flag_pass) : jsdifilter.flag_enabled, urlpattern: pattern, startline: 0, endline: 0 }; return filter; }, we then add the filters we want. ...
...nction that acts as a jsdifilter factory. function createfilter(pattern, pass) { var jsdifilter = components.interfaces.jsdifilter; var filter = { globalobject: null, flags: pass ? (jsdifilter.flag_enabled | jsdifilter.flag_pass) : jsdifilter.flag_enabled, urlpattern: pattern, startline: 0, endline: 0 }; return filter; }, we then add the filters we want. ...
JavaScript timers - Archive of obsolete content
indow for the next animation frame. documentation settimeout() calls a function or executes a code snippet after specified delay. setinterval() calls a function or executes a code snippet repeatedly, with a fixed time delay between each call to that function. setimmediate() calls a function immediately after the browser has completed other operations, such as events and display updates. cleartimeout() clears the delay set by settimeout(). clearinterval() cancels repeated action which was set up using setinterval(). clearimmediate() cancels the immediate actions, just like cleartimeout() for settimeout(). using javascript timers within animations (javascript daemons management) in computer science a daemon is a task that runs as a background process, rather than being under the ...
...to workers. this article provides a list of those. basic animations since we're using script to control canvas elements it's also very easy to make (interactive) animations. unfortunately the canvas element was never designed to be used in this way (unlike flash) so there are limitations. timer.jsm the timer.jsm javascript code module contains pure-javascript implementations of settimeout and cleartimeout that are compatible with the dom window functions, but that can be used by code that does not have access to a dom window (for example, javascript code modules or content frame scripts). ...
Chapter 3: Introduction to XUL—How to build a more intuitive UI - Archive of obsolete content
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. ...
...ge attribute allows you to display buttons with icons that are standard for the platform. possible values for the icon attribute are given in table 2. figure 8: a button with an image icon attribute value icon attribute value accept close cancel print help add open remove save refresh find go-forward clear go-back yes properties no select-font apply select-color table 2: values for the icon attribute toolbar buttons the toolbarbutton element is the element used to define toolbar buttons. this is typically placed inside a toolbar element, which defines a toolbar, but it can be used in other locations. these mostly act the same as button elements, but ...
JavaScript Object Management - Archive of obsolete content
meters, and the use of an alternate reference for this which we always name that. this is all necessary due to a javascript feature (quirk would be a better word for it) called method binding. the consequence of doing this wrong is to have a this reference that doesn't do what you expected it to do. there are a few workarounds for this, and we use the ones we have found to be the most elegant and clear to read. the general guideline we follow is this: whenever you have to set a callback function parameter, wrap it in an anonymous function. that is, something like function() { /* your code, usually a single function call. */ }. if you have to use a reference to this inside the function, declare a variable called that that equals this, and use that in the anonymous function. javascript has ...
...t is, something like function() { /* your code, usually a single function call. */ }. if you have to use a reference to this inside the function, declare a variable called that that equals this, and use that in the anonymous function. javascript has a host of features that make it extremely flexible, but it also has some disadvantages, as it is not as strict as other languages, such as java. a clear example of this is the fact that there are no private or public keywords that allow you to protect object members. as a alternative for this, a naming standard is frequently used to distinguish private and public members. there's no scope enforcement whatsoever, but this standard give others the chance to "play nice" and don't use private members. use "_" at the beginning of private attributes...
XPCOM Objects - Archive of obsolete content
he @mozilla.org/ prefix is just a way to keep things namespaced. we would use something like @xulschool.com/ to make our own components. components are either services (static objects) or instances of classes, just like the objects we handle in js. the method you call on cc["some-string"] should either be getservice or createinstance, depending on what you're asking for. in most cases it is very clear which one to call, but in case of doubt, look for documentation on it. those two methods always receive the interface identifier as an argument. similarly to cc, ci (components.interfaces) is an index of available interfaces. a modified version of the last code snippet produces an even longer list of available interfaces. just like in component identifiers, the nsi prefix is just a way of keepin...
...kely you'll have to do it in your own components. the second part defines a uuid for the interface. you must generate a new one for each interface, and you should change it every time the interface changes. in this case you're forced to use uuid, the email address format used for extension ids won't work. we included a constant, an attribute and a method to display examples of the 3, but this is clearly an overly elaborate way to keep a simple counter. you can define numeric and boolean constants in idl files, but not string constants. this is a known limitation of xpidl, and a simple workaround is to define a readonly attribute instead. this means you have to define a getter in the implementation file, though. you can access constants through a reference of the component, or directly from th...
Security best practices in extensions - Archive of obsolete content
this document is intended as a guide for developers to promote best practices in securing your extension. your goal is to keep your users safe. some items mentioned are strict guidelines, meaning that if you don't follow them then your add-on will not be approved on mozilla add-ons. other items are recommendations. the difference will be clearly flagged. this is written from the perspective of a firefox extension, but most items apply to extensions for other mozilla-based applications such as thunderbird or seamonkey. web content handling in general the best way to ensure that the browser is not compromised when you load content is to make sure it does not have those privileges. a more detailed explanation of this process is in displaying web content in an extension without security issue...
...ng known to the author. the convention for extensions is to use a chrome url for the site identifier, to avoid clashes with logins for sites. it could be the case that your extension provides a different tool or tools for services on your site. this approach is preferable because it provides users with a familiar interface for interacting with logins, via the firefox password manager. when users clear logins using the "clear recent history" option, it will include your extension's data. apis and other data handling web content is more than just pages, and more and more add-ons are interacting with web services via an application programming interface (api). many of the items talked about so far in this document apply in this sphere, but here are some additional tips: api providers should ...
MMgc - Archive of obsolete content
c reaped 114040 objects (3563 kb) freeing 903 pages (7800 kb) in 17.41 millis (2.0015 s) how mmgc works mark/sweep the mmgc garbage collector uses a mark/sweep algorithm. this is one of the most common garbage collection algorithms. every object in the system has an associated "mark bit." a garbage collection is divided into two phases: mark and sweep. in the mark phase, all of the mark bits are cleared. the garbage collector is aware of "roots", which are starting points from which all "live" application data should be reachable. the collector starts scanning objects, starting at the roots and fanning outwards. for every object it encounters, it sets the mark bit. when the mark phase concludes, the sweep phase begins. in the sweep phase, every object that wasn't marked in the mark phase is de...
...claimed. if an object didn't have its mark bit set during the mark phase, that means it wasn't reachable from the roots anymore, and thus was not reachable from anywhere in the application code. the following flash animation illustrates the working of a mark/sweep collector: (temporarily not working) <gflash>600 300 gc.swf</gflash> one pass the mark sweep algorithm described above decomposes into clearmarks/mark/finalize/sweep. in our original implementation clearmarks/finalize/sweep visited every gc page and every object on that page. 3 passes! now we have one pass where marks are cleared during sweep so clear marks isn't needed at the start. also finalize builds up a lists of pages that need sweeping so sweep doesn't need to visit every page. this has been shown to cut the finalize/sweep paus...
Block and Line Layout Cheat Sheet - Archive of obsolete content
" flags), and flags that are reserved for an individual frame's private use ("private" flags). ns_frame_in_reflow this bit is set when the frame is being actively being reflowed. by default it is set in willreflow(), and unset in didreflow(). many frames' reflow() method verifies that the bit is set with an assertion. ns_frame_first_reflow this flag is set on a newly created frame, and later cleared by the frame's reflow() method when the frame has had its initial reflow. ns_frame_sync_frame_and_view ns_frame_outside_children this flag is set if the combined area of a frame's children extend past the frame's bounding box. (what is a frame's "bounding box"?) if this flag is set, then <code>moverflowarea</code> will contain the total area of the frame, including the overflow. ns_frame_e...
... final size. e.g., because...why? brs_isinlineincrreflow this flag is set in nsblockframe::reflow() if we detect that we're incrementally reflowing a linebox that contains inline frames. in this case, we can avoid some of the work that occurs during reflow. brs_nowrap this flag is set in the nsblockreflowstate constructor when the "white-space" style of the block frame is pre or nowrap. it is cleared, otherwise. brs_istopmarginroot this flag is set in the nsblockreflowstate constructor when reflowing a "block margin root" frame (i.e., a frame with the ns_block_margin_root flag set, for which margins apply by default). the flag is also set when reflowing a frame whose computed top border padding is zero. (why?) brs_isbottommarginroot this flag is set in the nsblockreflowstate constructor...
Layout System Overview - Archive of obsolete content
l or xml document could be viewed as a normal galley presentation in a browser window, while simultaneously being presented in a paged presentation to a printer, or even an aural presentation to a speech-synthesizer. to date the only real use of this multiple presentation ability is seen in printing, where multiple presentations are managed, all connected to the same content model. (note: it is unclear if this is really a benefit - it may have been better to use a copy of the content model for each presentation, and to remove the complexity of managing separate presentations - analysis is needed here). the idea of supporting a non-visual presentation is interesting. layout's support for aural presentations is undeveloped, though conceptually, it is possible and supported by the architecture. ho...
...ents for the details on all of the classes, in the context of their actual role). presentation shell / presentation context together the presentation shell and the presentation context provide the root of the current presentation. the original design provided for a single presentation shell to manage multiple presentation contexts, to allow a single shell to handle multiple presentations. it is unclear if this is really possible, however, and in general it is assumed that there is a one-to-one correspondence between a presentation shell and a presentation context. the two classes should probably be folded into one, or the distinction between them formalized and utilized in the code. the presentation shell currently owns a controlling reference to the presentation context. further references to ...
New Security Model for Web Services - Archive of obsolete content
t the user -- to determine whether a resource should be insulated from web applications loaded from outside of the firewall. using a soap header for verification soap messages have a distinct processing model allowing a header to be added that the recipient is required to understand and accept, which identifies the untrusted source of a script making a request. soap services which have not been cleared for access by untrusted scripts will reject the requests. this is offered in the mozilla implementation of soap today. unfortunately, this does not prevent soap messages from being sent to non-soap addresses, which is a big enough problem that the verification cannot stand alone to guarantee that untrusted service requests are always properly rejected by services that should be firewall-protec...
...ipts access file, which seems undesirable. on the other hand, perhaps it is not so bad, since it permits independent management in domains where the top level owner may not care about providing access to web services. adjustments as this new model is applied to soap, and potentially document.load or xml-request, it may be desirable to eliminate the same source security bypass, because it is not clear that this is always secure. other security adjustments may be desired as well. feedback? please send me some feedback on this proposal see also mozilla web services security model - documentation of what is currently implemented ...
Space Manager High Level Design - Archive of obsolete content
ion of this. data model class/component diagram nsspacemanager: the central point of management of the space taken up by floats in a block nsbanddata: provides information about the frames occupying a band of occupied or available space nsblockbanddata: a specialization of nsbanddata that is used by nsblockreflowstate to determine the available space, float impacts, and where floats are cleared. essentially a css-specific wrapper for generic nsbanddata. bandrect: keeps the bounds of a band, along with the frames associated with the band. bandrects are a linked list (provided by prcliststr super-class) and also provide some geometry-management methods (splitvertically, splithorizontally) and some methods that query or manipulate the frames associated with the band (isoccupiedby, addfr...
... problems / bugs found during documentation: bandrect and bandlist are public in nsspacemanager.h - should be private (compiles fine) nsspacemanager data members are declared protected, but there are no subclasses. ...
Supporting per-window private browsing - Archive of obsolete content
relevant window is the one that contains the chrome element. in some cases, there is no logical window object to use (such as when data or an action originate from some other source than web content). in these cases, it is permissable to pass null as the argument instead of a real privacy context. however, this can lead to privacy leaks (such as cache and download entries) if not used carefully. ...
...ad to privacy leaks (such as cache and download entries) if not used carefully. clearing any temporarily-stored private data it is permissable to store private data in non-persistent ways for the duration of a private browsing session. to be notified when such a session ends (i.e., when the last private window is closed), observe the last-pb-context-exited notification. ...
Example Sticky Notes - Archive of obsolete content
e> </head> <body> <h1><a href="http://developer.mozilla.org/en/docs/xbl:xbl_1.0_reference">xbl</a> demo : sticky notes</h1> <div class="sticker"><p>acme,&nbsp;inc. ...
...window.alert(str); ]]></handler> <handler event="mouseover"><![cdata[ this.$bg = this.style.backgroundcolor || '#ffff00'; this.style.backgroundcolor = '#ffcc00'; ]]></handler> <handler event="mouseout"><![cdata[ this.style.backgroundcolor = this.$bg; ]]></handler> </handlers> </binding> </bindings> notes.css .sticker { position: relative; left: 0px; right: 0px; float: left; clear: none; width: 10em; height: 10em; overflow: visible; margin: 1em 1em; padding: 0.5em 0.5em; border: 2px solid blue; background-color: yellow; font: 1em normal "times new roman",serif; font-style: italic; cursor: default; } view this example ...
Sorting and filtering a custom tree view - Archive of obsolete content
xt/css"?> <!doctype window> <window title="sorting a custom tree view example" xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul" onload="init()"> <script type="application/javascript" src="sort.js"/> <hbox align="center" id="search-box"> <label accesskey="f" control="filter">filter</label> <textbox id="filter" oninput="inputfilter(event)" flex="1"/> <button id="clearfilter" oncommand="clearfilter()" label="clear" accesskey="c" disabled="true"/> </hbox> <tree id="tree" flex="1" persist="sortdirection sortresource" sortdirection="ascending" sortresource="description"> <treecols> <treecol id="name" label="name" flex="1" persist="width ordinal hidden" onclick="sort(this)" class="sortdirectionindicator" sortdirection="ascending"/> <splitter class="tree-...
...lowercase(); } return o; } function gettopvisiblerow() { return tree.treeboxobject.getfirstvisiblerow(); } function settopvisiblerow(topvisiblerow) { return tree.treeboxobject.scrolltorow(topvisiblerow); } function inputfilter(event) { //do this now rather than doing it at every comparison var value = prepareforcomparison(event.target.value); setfilter(value); document.getelementbyid("clearfilter").disabled = value.length == 0; } function clearfilter() { document.getelementbyid("clearfilter").disabled = true; var filterelement = document.getelementbyid("filter"); filterelement.focus(); filterelement.value = ""; setfilter(""); } function setfilter(text) { filtertext = text; loadtable(); } ...
Additional Template Attributes - Archive of obsolete content
template container="?first" member="?item"> the container and member attributes can be used to specify the container and member variables. this isn't particularly useful although there is a very slight optimization since the builder does not need to scan the action body looking for the member variable when compiling the queries and rules. you might also use these attributes just to make the code clearer when using very complex queries. one possible advantage is when using the simple rdf query syntax where you don't specify variables; instead you use the special 'rdf:*' syntax for the member variable and the container is implied. by using the container and member attributes, you can use specific variables instead. <hbox datasources="template-guide-photos5.rdf" ref="http://www.xulplanet.
...ad. <hbox datasources="template-guide-photos5.rdf" ref="http://www.xulplanet.com/rdf/myphotos"> <template container="?start" member="?photo"> <rule> <image uri="?photo" src="?photo"/> </rule> </template> </hbox> in this example, the ?photo variable can be used instead of 'rdf:*' (although you can use either even if you specify the member variable). this may make the code clearer as to its function. we could use the container variable ?start in the action body also. if you are using the simple syntax and want to use the container variable in the content, you must use the container attribute since there is no other way to refer to it. note also that a rule element is needed here, otherwise the builder will think the container and member attributes are conditions to check...
Textbox (XPFE autocomplete) - Archive of obsolete content
this should be one of the characters that...
...attributenodens(), setattributens(), setuserdata addsession( session ) obsolete since gecko 26 return type: nsiautocompletesession adds a new session object to the autocomplete widget. this can be used to create a customized autocomplete results list. the argument should be an object which implements the nsiautocompletesession interface. this method returns the object passed in. clearresults() return type: ??? clears the results list. getdefaultsession return type: session name returns the name of the first session with available results. getresultat( index ) obsolete since gecko 26 return type: nsiautocompleteitem returns the result item at the specified index. the item will be a value of type nsiautocompleteitem. getresultcount( session ) returns ...
Tree Widget Changes - Archive of obsolete content
ion object from the view, not the box object, meaning use tree.view.selection instead of tree.treeboxobject.selection. use tree.columns[1].id instead of tree.treeboxobject.getcolumnid(1) to get the id of a column, in this case column 1. use tree.columns.getkeycolumn().index instead of tree.treeboxobject.getkeycolumnindex(). the nsitreeboxobject.getpagecount() method has been renamed to make it clearer what it does. it returns the number of rows that can be displayed in the tree. this should correspond to the rows attribute on the tree if it was specified. tree.treeboxobject.getpagecount() is now tree.treeboxobject.getpagelength(). the invalidateprimarycell(row) method has been removed, instead use nsitreeboxobject.invalidatecell() like this invalidatecell(row, tree.columns.getprimarycolumn...
...been replaced with a single method candrop(idx,orientation) which handles both. it should return true if a drop is allowed on a row. checkbox columns tree columns now implement the checkbox type. previously the value existed but was not implemented. now it is. you can create a checkbox column by setting the type attribute of a column to checkbox. <treecol type="checkbox"> you can then set or clear the checkbox for a particular cell in that column by setting the value attribute to true, or leaving out the attribute. note that it's the value attribute you use, not the label attribute. <treecell/> <treecell value="true"/> you need to specify the checkbox image with css for the checkbox to display. (do not set id of the column to be 'checked' it will cause problems with the css) treechildr...
Tabboxes - Archive of obsolete content
this takes up more room. the area taken up by the tab area does not change when the user switches to a new tab page. tabbox example example 1 : source view <tabbox> <tabs> <tab label="mail"/> <tab label="news"/> </tabs> <tabpanels> <tabpanel id="mailtab"> <checkbox label="automatically check for mail"/> </tabpanel> <tabpanel id="newstab"> <button label="clear news buffer"/> </tabpanel> </tabpanels> </tabbox> here, two tabs have been added, the first labeled 'mail' and the other 'news'. when the user clicks on the mail tab, the contents of the first tab page will be displayed below the tabs. in this case, the page with the check box labeled 'automatically check for mail' will appear. when the second tab is clicked, the page containing the butto...
...r"/> </tabpanel> </tabpanels> </tabbox> here, two tabs have been added, the first labeled 'mail' and the other 'news'. when the user clicks on the mail tab, the contents of the first tab page will be displayed below the tabs. in this case, the page with the check box labeled 'automatically check for mail' will appear. when the second tab is clicked, the page containing the button labeled 'clear news buffer' will appear instead. the currently selected tab element is given an additional selected attribute which is set to true. this alters the appearance of the currently selected tab to make it look selected. only one tab will have a true value for this attribute at a time. position of the tabs finally, you can change the position of the tabs so that they appear on any side of the tab p...
Tree Selection - Archive of obsolete content
t you should not just change the tree's currentindex property to change the selection. instead, you should use the selection's select function as in the example above. you can select all rows with the selectall() function. note that rows nested inside containers that are not open will not be selected. naturally, this will only have any effect for trees that use multiple selection. there is also a clearselection() function to clear the selection, and an invertselection function to reverse the selection, that is, deselect all selected rows and select all unselected rows. to select specific rows, use the rangedselect() function which selects all rows in between two indices. here is an example which selects rows between index 2 and 7. note that rows 2 and 7 will also be selected. tree.view.selectio...
...ts all rows in between two indices. here is an example which selects rows between index 2 and 7. note that rows 2 and 7 will also be selected. tree.view.selection.rangedselect(2,7,true); the last argument indicates whether to add to the current selection or not. if true, the range will be added to the existing selection. if false, all existing selected rows will be deselected first. finally, the clearrange() function may be used to deselect a range of rows, leaving rows outside the range unaffected. tree.view.selection.clearrange(2,7); next, we'll find out how to create a custom view for a tree. « previousnext » ...
XUL accessibility guidelines - Archive of obsolete content
ble to use and enjoy them. accessibility is not difficult, but does require a basic understanding of the different types of disabilities, commonly used assistive technologies, and special accessibility features built into the xul languages. most of all, accessibility requires a conscious effort on your part, and a desire to include everyone. it is hoped that these guidelines will be sufficiently clear and detailed that everyone—even someone with no previous background in accessibility—can understand them. in addition, there is an active community of accessibility developers within the mozilla project that will be happy to help you with any concerns or questions you have in regards to making your xul applications fully accessible. there is also a xul accessibility tool which can help test ...
...uch as the high-contrast theme on windows, available via left-alt + left-shift + printscreen). confirm that text is emphasized correctly and that color is not used as a sole means to convey meaning. ensure that when windows are resized, the application adjusts gracefully. human computer interaction as you use an application you expect a certain amount of control and feedback. provide users with clear instruction and feedback, and allow users to correct errors. some users with disabilities have difficulties with quick responses. allow users adequate time to perform tasks. instruction provide users with help documentation. even simple applications should include a help document or manual for user reference. describe keyboard shortcuts and any other accessibility considerations. users should b...
calICalendarViewController - Archive of obsolete content
hange the attributes of an already existing caliitem. the calidatetime parameters must either both be specified, or neither. if they are both specified, aoccurrence should be modified 'silently', that is, without a more detailed dialog appearing. otherwise, a dialog should be display allowing the user to modify the fields. ...
...alicalendarviewcontroller should be careful to provide clearly defined behavior to the user regarding the modification of recurring caliitems. deleteoccurrence void deleteoccurrence (in caliitemoccurrence aoccurrence); the deleteoccurrence method is called when by the calicalendarview when caliitem should be deleted. implementations of calicalendarviewcontroller should be careful to provide clearly defined behavior to the user regarding the deleting of recurring caliitems, in the case where aoccurrence is a single occurrence of a recurring caliitem. related interfaces calicalendarview calidecoratedview example code var myviewcontroller = { queryinterface: function(aiid) { if (!aiid.equals(components.interfaces.calicalendarviewcontroller) && !aiid.equals(compo...
Extentsions FAQ - Archive of obsolete content
erences set by extension? if not, how to proceed? when user chooses to uninstall an extension, a nsiobserverservice notification is sent out. the problem is, while your extension is still active, user can cancel uninstallation, and when it is physically uninstalled, your code can't run. right. and if you uninstall firefox, the profile data is left behind. it would be nice to give the option of clearing extension's data, but it should be implemented at application level, not by each extension individually. it might be an option to stick with it and perform stuff when it comes to application shutdown. the sanitize stuff does this (clean stuff on exit). http://lxr.mozilla.org/mozilla1.8/so...ents/nsbrowser... firefox will clean all those preferences which are still "default", that is not ...
... the sanitize stuff does this (clean stuff on exit). http://lxr.mozilla.org/mozilla1.8/so...ents/nsbrowser... firefox will clean all those preferences which are still "default", that is not changed by the user or the application/extension. to provide those default preferences to your extension see: http://kb.mozillazine.org/dev_:_usin...lt_preferences btw: resetting prefences to default will clear them in case no default prefence is (still) available. those will be completely removed upon next application launch. is it possible to create a sidebar on the top of the page? not unless you make it a separate window. there's a bug in bugzilla about stacking other widgets on top of browser/iframe, which hopefully will be fixed for gecko 1.9. could someone write an extension that zaps the...
Sunbird Theme Tutorial - Archive of obsolete content
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 directory is your theme directory. go into your theme directory. creating information about your theme in your theme directory, create a plain text file named <tt>install.rdf</tt>. copy and paste the...
...ose tools – themes... in the themes window, check that your new theme has appeared. select it and press the use theme button. restart sunbird again. if your theme is working, you see the effect of the changes that you made. developing your theme to develop your theme, make further changes to the theme files. you might prefer to do some design work in an image editor first, so that you have a clear design concept to implement. understanding sunbird's user interface to understand sunbird's user interface, go to sunbird's program directory, then to the <tt>chrome/content/calendar</tt> directory there. examine the files there to understand how sunbird's user interface is constructed. the basic interface is written in xul, but some parts are constructed using xbl or javascript. to discover d...
-ms-wrap-flow - Archive of obsolete content
leave empty the area after the end edge of the exclusion area. end inline flow content can wrap after the end edge of the exclusion area but must leave empty the area before the start edge of the exclusion area. maximum inline flow content can wrap on the side of the exclusion with the largest available space for the given line, and must leave empty the other side of the exclusion. clear inline flow content can only wrap on top and bottom of the exclusion and must leave empty the areas to the start and end edges of the exclusion box. formal syntax auto | both | start | end | maximum | clear specifications not part of any specification. remarks the -ms-wrap-flow property makes an element an exclusion element when it has a computed value other than auto. this property ...
...ntent will wrap around the exclusion in a way similar to how it wraps around floated elements. when the -ms-wrap-flow property's computed value is auto, the element does not become an exclusion element unless its float property's computed value is not none. in that case, the element contributes its border box to its containing block's wrapping context and content flows around it according to the clear property. for more information about the impact of an exclusion element on content flow, see the terminology section of the css exclusions module level 1 specification. ...
Index - Game development
ame development, gamedev, games, html5 games, javascript games, web gaming is one of the most popular computer activities. new technologies are constantly arriving to make it possible to develop better and more powerful games that can be run in any standards-compliant web browser. 2 anatomy of a video game games, javascript, main loop, requestanimationframe i want to be clear that any of the above, or none of them, could be best for your game. the correct decision entirely depends on the trade-offs that you are willing (and unwilling) to make. the concern is mostly with switching to another option. fortunately, i do not have any experience with this, but i have heard it is an excruciating game of whack-a-mole. 3 examples demos, example, games, web ...
...lly finished, so let's work on polishing it up. we have already added keyboard controls, but we could easily add mouse controls too. 67 move the ball 2d, beginner, canvas, games, javascript, loop, tutorial, movement you already know how to draw a ball from working through the previous article, so now let's make it move. technically, we will be painting the ball on the screen, clearing it and then painting it again in a slightly different position every frame to make the impression of movement — just like how movement works with the movies. 68 paddle and keyboard controls beginner, canvas, controls, games, graphics, javascript, tutorial, keyboard the ball is bouncing off the walls freely and you can watch it indefinitely, but currently there's no inter...
Building up a basic demo with Babylon.js - Game development
lobal object contains all the babylon.js functions available in the engine. creating a scene a scene is the place where all the game content is displayed. while creating new objects in the demo, we will be adding them all to the scene to make them visible on the screen. let's create a scene by adding the following lines just below our previous code: var scene = new babylon.scene(engine); scene.clearcolor = new babylon.color3(0.8, 0.8, 0.8); thus, the scene is created and the second line sets the background color to light gray. creating a rendering loop to make the scene actually visible we have to render it. add these lines at the end of the <script> element, just before the closing </script>. var renderloop = function () { scene.render(); }; engine.runrenderloop(renderloop); we'r...
...hod to execute the renderloop() function repeatedly on every frame — the loop will continue to render indefinitely until told to stop. creating a camera now the setup code is in place we need to think about implementing the standard scene components: camera, light and objects. let's start with the camera — add this line to your code below the scene creation and the line where we defined the clearcolor. var camera = new babylon.freecamera("camera", new babylon.vector3(0, 0, -10), scene); there are many cameras available in babylon.js; freecamera is the most basic and universal one. to initialize it you need to pass it three parameters: any name you want to use for it, the coordinates where you want it to be positioned in the 3d space, and the scene you want to add it to. note: you pro...
Building up a basic demo with the PlayCanvas engine - Game development
ur script. app.setcanvasfillmode(pc.fillmode_fill_window); app.setcanvasresolution(pc.resolution_auto); camera now when the setup code is in place we need to think about implementing the standard scene components: camera, lights and objects. let's start with the camera — add these lines to your code, below the previous ones. ...
...next, the camera object is added to the root of our application and positioned to be 7 units away from the center of the scene on the z axis. this allows us to make some space to visualize the objects that we will create later on. note: the distance values (e.g. ...
Building up a basic demo with Three.js - Game development
hing is rendered, so the webgl implementation will implement differently than the css one. despite the variety of ways they achieve the goal, the experience will look the same for the user. thanks to this approach, a fallback can be used, if a desired technology is not supported by the browser. ...
... add this code into our second <script> element, just below the javascript comment. scene a scene is the place where everything happens. when creating new objects in the demo, we add them all inside the scene to become visible on the screen. ...
GLSL Shaders - Game development
. demo let's build a simple demo to explain those shaders in action. be sure to read three.js tutorial first to grasp the concept of the scene, its objects, and materials. note: remember that you don't have to use three.js or any other library to write your shaders — pure webgl (web graphics library) is more than enough. we've used three.js here to make the background code a lot simpler and clearer to understand, so you can just focus on the shader code. three.js and other 3d libraries abstract a lot of things for you — if you wanted to create such an example in raw webgl, you'd have to write a lot of extra code to actually make it work. environment setup to start with the webgl shaders you don't need much. you should: make sure you are using a modern browser with good webgl suppo...
...+10.0, position.y, position.z+5.0, 1.0); } </script> <script id="fragmentshader" type="x-shader/x-fragment"> void main() { gl_fragcolor = vec4(0.0, 0.58, 0.86, 1.0); } </script> javascript var width = window.innerwidth; var height = window.innerheight; var renderer = new three.webglrenderer({antialias:true}); renderer.setsize(width, height); renderer.setclearcolor(0xdddddd, 1); document.body.appendchild(renderer.domelement); var scene = new three.scene(); var camera = new three.perspectivecamera(70, width/height); camera.position.z = 50; scene.add(camera); var boxgeometry = new three.boxgeometry(10, 10, 10); var shadermaterial = new three.shadermaterial( { vertexshader: document.getelementbyid( 'vertexshader' ).
Desktop mouse and keyboard controls - Game development
) { uppressed = true; } } the keyuphandler looks almost exactly the same as the keydownhandler above, but instead of setting the pressed variables to true, we would set them to false. ...
...then the pressed key variables are checked and the playerx and playery variables (that we define earlier just after leftpressed and the others) holding the position of the ship are adjusted by a given amount, let's say 5 pixels. ...
Implementing controls using the Gamepad API - Game development
to act accordingly — for example when we have a two-player game requiring two devices to be connected. querying the gamepad object beside connect() and disconnect(), there are two more methods in the gamepadapi object: update() and buttonpressed(). ...
...(). ...
asm.js - Game development
hings like `while`, `if`, numbers, top-level named functions, and other simple constructs. it does not allow objects, strings, closures, and basically anything that requires heap allocation. asm.js code resembles c in many ways, but it's still completely valid javascript that will run in all current engines. it pushes js engines to optimize this kind of code, and gives compilers like emscripten a clear definition of what kind of code to generate. we will show what asm.js code looks like and explain how it helps and how you can use it. this subset of javascript is already highly optimized in many javascript engines using fancy just-in-time (jit) compiling techniques. however, by defining an explicit standard we can work on optimizing this kind of code even more and getting as much performance a...
...jit) compiling techniques. however, by defining an explicit standard we can work on optimizing this kind of code even more and getting as much performance as we can out of it. it makes it easier to collaborate across multiple js engines because it's easy to talk about and benchmark. the idea is that this kind of code should run very fast in each engine, and if it doesn't, it's a bug and there's a clear spec that engines should optimize for. it also makes it easy for people writing compilers that want to generate high-performant code on the web. they can consult the asm.js spec and know that it will run fast if they adhere to asm.js patterns. emscripten, a c/c++ to javascript compiler, emits asm.js code to make it run with near native performance on several browsers. additionally, if an engine...
Game over - Game development
ert message and restarting the game by reloading the page. first, replace where you initially called setinterval() setinterval(draw, 10); with: var interval = setinterval(draw, 10); then replace the second if statement with the following: if(y + dy < ballradius) { dy = -dy; } else if(y + dy > canvas.height-ballradius) { alert("game over"); document.location.reload(); clearinterval(interval); // needed for chrome to end game } letting the paddle hit the ball the last thing to do in this lesson is to create some kind of collision detection between the ball and the paddle, so it can bounce off it and get back into the play area. the easiest thing to do is to check whether the center of the ball is between the left and right edges of the paddle. update the last bit ...
...check whether the center of the ball is between the left and right edges of the paddle. update the last bit of code you modified again, to the following: if(y + dy < ballradius) { dy = -dy; } else if(y + dy > canvas.height-ballradius) { if(x > paddlex && x < paddlex + paddlewidth) { dy = -dy; } else { alert("game over"); document.location.reload(); clearinterval(interval); } } if the ball hits the bottom edge of the canvas we need to check whether it hits the paddle . if yes, then it 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...
Accessible multimedia - Learn web development
unity or team in your workplace, then you could ask them for help with doing the translations. you could even have a go at doing them yourself. automated services — there are ai services available, like trint or transcribear. upload a video/audio file to the site, and it automatically transcribes it for you. on youtube you can choose to generate automated captions/transcripts. depending on how clear the spoken audio is, the resulting transcript quality will vary greatly. as with most things in life, you tend to get what you pay for; different services will vary in accuracy and time taken to produce the transcript. if you pay a reputable company or ai service to do the transcription, you will probably get it done rapidly and to a high quality. if you don't want to pay for it, you are likel...
...owever, other multimedia is not so easy to make accessible. if for example you are dealing with an immersive 3d game or virtual reality app, it really is quite difficult to provide text alternatives for such an experience, and you might argue that blind users are not really in the target audience bracket for such apps. you can however make sure that such an app has good enough color contrast and clear presentation so it is perceivable to those with low vision/color blindness, and also make it keyboard accessible. remember that accessibility is about doing as much as you can, rather than striving for 100% accessibility all the time, which is often impossible. test your skills! you've reached the end of this article, but can you remember the most important information? we've not written a new...
Introduction to CSS layout - Learn web development
out; to find out more see our grid layout article. the rest of this guide covers other layout methods, which are less important for the main layout structures of your page but can still help you achieve specific tasks. by understanding the nature of each layout task, you will soon find that when you look at a particular component of your design the type of layout best suited to it will often be clear. floats floating an element changes the behavior of that element and the block level elements that follow it in normal flow. the element is moved to the left or right and removed from normal flow, and the surrounding content floats around the floated item. the float property has four possible values: left — floats the element to the left. right — floats the element to the right. none ...
...m erat volutpat. suspendisse ac imperdiet turpis. aenean finibus sollicitudin eros pharetra congue. duis ornare egestas augue ut luctus. proin blandit quam nec lacus varius commodo et a urna. ut id ornare felis, eget fermentum sapien.</p> .box { float: left; width: 150px; height: 150px; margin-right: 30px; } note: floats are fully explained in our lesson on the float and clear properties. prior to techniques such as flexbox and grid layout floats were used as a method of creating column layouts. you may still come across these methods on the web; we will cover these in the lesson on legacy layout methods. positioning techniques positioning allows you to move an element from where it would be placed when in normal flow to another location. positioning isn’t a metho...
Legacy layout methods - Learn web development
creating simple legacy grid frameworks the majority of legacy frameworks use the behavior of the float property to float one column up next to another in order to create something that looks like a grid. working through the process of creating a grid with floats shows you how this works and also introduces some more advanced concepts to build on the things you learned in the lesson on floats and clearing. the easiest type of grid framework to create is a fixed width one — we just need to work out how much total width we want our design to be, how many columns we want, and how wide the gutters and columns should be. if we instead decided to lay out our design on a grid with columns that grow and shrink according to browser width, we would need to calculate percentage widths for the columns a...
...ths — in this case, the padding is subtracted from the total content width because we have set box-sizing to border-box on all elements on the site (see changing the box model completely for more explanation). * { box-sizing: border-box; } body { width: 980px; margin: 0 auto; } .wrapper { padding-right: 20px; } now use the row container that is wrapped around each row of the grid to clear one row from another. add the following rule below your previous one: .row { clear: both; } applying this clearing means that we don’t need to completely fill each row with elements making the full twelve columns. the rows will remain separated, and not interfere with each other. the gutters between the columns are 20 pixels wide. we create these gutters as a margin on the left side of eac...
Styling links - Learn web development
ks different to the default styling, but it still provides a familiar enough experience for users to know what's going on: the first two rules are not that interesting to this discussion. the third rule uses the a selector to get rid of the default text underline and focus outline (which varies across browsers anyway), and adds a tiny amount of padding to each link — all of this will become clear later on. next, we use the a:link and a:visited selectors to set a couple of color variations on unvisited and visited links, so they are distinct. the next two rules use a:focus and a:hover to set focused and hovered links to have different background colors, plus an underline to make the link stand out even more. two points to note here are: the underline has been created using border-b...
...being underlined (e.g. the tails on g and y). the border-bottom value has been set as 1px solid, with no color specified. doing this makes the border adopt the same color as the element's text, which is useful in cases like this where the text is a different color in each case. finally, a:active is used to give the links an inverted color scheme while they are being activated, to make it clear something important is happening! active learning: style your own links in this active learning session, we'd like you to take our empty set of rules and add your own declarations to make the links look really cool. use your imagination, go wild. we are sure you can come up with something cooler and just as functional as our example above. if you make a mistake, you can always reset it using ...
How do I start to design my website? - Learn web development
ue 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 following questions. note: there are countless ways to carry out project ideation. we cannot lay them all out here (a whole book wouldn't be enough). what we will present here is a simple method to handle what professionals call project ideation, project pla...
...rd-party services?) conclusion as you can see, the simple idea "i want to make a website" generates a long to-do list, which only grows longer as you think about it. soon it may look overwhelming, but don't panic. you don't need to answer all the questions and you don't need to do everything on your list. what matters is to have a vision of what you want and how to get there. once you have that clear vision, you need to decide how and when to do it. break down big tasks into small, actionable steps. and those small steps will add up to great achievements. from this article, you should now be able to make a rough plan for creating a website. a next step might be to read how the internet works. ...
Client-side form validation - Learn web development
alidation api.you're still able to use javascript to validate your form, but you'll just have to write your own. to validate a form, ask yourself a few questions: what kind of validation should i perform? you need to determine how to validate your data: string operations, type conversion, regular expressions, and so on. it's up to you. what should i do if the form doesn't validate? this is clearly a ui matter. you have to decide how the form will behave. does the form send the data anyway? should you highlight the fields that are in error? should you display error messages? how can i help the user to correct invalid data? in order to reduce the user's frustration, it's very important to provide as much helpful information as possible in order to guide them in correcting their inputs. y...
...d the data anyway? should you highlight the fields that are in error? should you display error messages? how can i help the user to correct invalid data? in order to reduce the user's frustration, it's very important to provide as much helpful information as possible in order to guide them in correcting their inputs. you should offer up-front suggestions so they know what's expected, as well as clear error messages. if you want to dig into form validation ui requirements, here are some useful articles you should read: smashingmagazine: form-field validation: the errors-only approach smashingmagazine: web form validation: best practices and tutorials six revision: best practices for hints and validation in web forms a list apart: inline validation in web forms an example that d...
The HTML5 input types - Learn web development
ields are intended to be used to create search boxes on pages and apps. this type of field is set by using the value search for the type attribute: <input type="search" id="search" name="search"> the main difference between a text field and a search field is how the browser styles its appearance. ...
...d with rounded corners; they also sometimes display an "Ⓧ", which clears the field of any value when clicked). additionally, on devices with dynamic keyboards, the keyboard's enter key may read "search", or display a magnifying glass icon. the below screenshots show a non-empty search field in firefox 71, safari 13, and chrome 79 on macos, and edge 18 and chrome 79 on windows 10. note that the clear icon only appears if the field has a value, and, apart from safari, it is only displayed when the field is focused. another feature worth noting is that the values of a search field can be automatically saved and re-used to offer auto-completion across multiple pages of the same website; this tends to happen automatically in most modern browsers. phone number field a special field for fillin...
Creating hyperlinks - Learn web development
e.com/projects/pdfs/project-brief.pdf. of course, the location of the project-brief.pdf file and pdfs folder won't suddenly change because you moved the index.html file — this would make your link point to the wrong place, so it wouldn't work if clicked on. you need to be careful! link best practices there are some best practices to follow when writing links. let's look at these now. use clear link wording it's easy to throw links up on your page. that's not enough. we need to make our links accessible to all readers, regardless of their current context and which tools they prefer. for example: screenreader users like jumping around from link to link on the page, and reading links out of context. search engines use link text to index target files, so it is a good idea to include k...
...web works for more information). then it goes to that server and finds the file that's being requested. with a relative url, the browser just looks up the file that's being requested on the same server. if you use absolute urls where relative urls would do, you're constantly making your browser do extra work, meaning that it will perform less efficiently. linking to non-html resources — leave clear signposts when linking to a resource that will be downloaded (like a pdf or word document), streamed (like video or audio), or has another potentially unexpected effect (opens a popup window, or loads a flash movie), you should add clear wording to reduce any confusion. for example: if you're on a low bandwidth connection, click a link, and then a multiple megabyte download starts unexpected...
Introduction to events - Learn web development
vironments. a series of fortunate events as mentioned above, events are actions or occurrences that happen in the system you are programming — the system produces (or "fires") a signal of some kind when an event occurs, and provides a mechanism by which an action can be automatically taken (that is, some code running) when the event occurs. for example, in an airport, when the runway is clear for take off, a signal is communicated to the pilot. as a result, the plane can safely takeoff. in the case of the web, events are fired inside the browser window, and tend to be attached to a specific item that resides in it — this might be a single element, set of elements, the html document loaded in the current tab, or the entire browser window. there are many different types of events t...
...ally — it doesn't sound that different, but the code is quite different, making use of functions like on() to register an event listener, and once() to register an event listener that unregisters after it has run once. the http connect event docs provide a good example. you don't need to understand anything about other such environments at this stage in your learning; we just wanted to make it clear that events can differ in different programming environments. ways of using web events there are a number of ways to add event listener code to web pages so it runs when the associated event fires. in this section, we review the various mechanisms and discuss which ones you should use. event handler properties these are the properties that exist to contain event handler code we have seen most...
Introduction to web APIs - Learn web development
le, think about the electricity supply in your house, apartment, or other dwellings. if you want to use an appliance in your house, you simply plug it into a plug socket and it works. you don't try to wire it directly into the power supply — to do so would be really inefficient and, if you are not an electrician, difficult and dangerous to attempt. image source: overloaded plug socket by the clear communication people, on flickr. in the same way, if you want to say, program some 3d graphics, it is a lot easier to do it using an api written in a higher-level language such as javascript or python, rather than try to directly write low level code (say c or c++) that directly controls the computer's gpu or other graphics functions. note: see also the api glossary entry for further descripti...
...llows you to do things like displaying your latest tweets on your website. it provides a special set of constructs you can use to query the twitter service and return specific information. relationship between javascript, apis, and other javascript tools so above, we talked about what client-side javascript apis are, and how they relate to the javascript language. let's recap this to make it clearer, and also mention where other javascript tools fit in: javascript — a high-level scripting language built into browsers that allows you to implement functionality on web pages/apps. note that javascript is also available in other programming environments, such as node. browser apis — constructs built into the browser that sits on top of the javascript language and allows you to implemen...
Ember interactivity: Events, classes and state - Learn web development
need a place to store todos so that other components can access them. storing todos with a service ember has built-in application-level state management that we can use to manage the storage of our todos and allow each of our components to access data from that application-level state. ember calls these constructs services, and they live for the entire lifetime of the page (a page refresh will clear them; persisting the data for longer is beyond the scope of this tutorial). run this terminal command to generate a service for us to store our todo-list data in: ember generate service todo-data this should give you a terminal output like so: installing service create app/services/todo-data.js installing service-test create tests/unit/services/todo-data-test.js this creates a todo-data.
...he <input> is properly reflected in the ui: summary ok, so that's great progress for now. we can now add todo items to our app, and the state of the data is tracked using our service. next we'll move on to getting our footer functionality working, including the todo counter, and look at conditional rendering, including correctly styling todos when they've been checked. we'll also wire up our "clear completed" button. previous overview: client-side javascript frameworks next in this module introduction to client-side frameworks framework main features react getting started with react beginning our react todo list componentizing our react app react interactivity: events and state react interactivity: editing, filtering, conditional rendering accessibility ...
Getting started with React - Learn web development
tand this file at all to complete this tutorial, however, if you'd like to learn more about it, you can read what is the file `package.json`? on nodejs.org; we also talk about it in our package management basics tutorial. exploring our first react component — <app/> in react, a component is a reusable module that renders a part of our app. these parts can be big or small, but they are usually clearly defined: they serve a single, obvious purpose. let's open src/app.js, since our browser is prompting us to edit it. this file contains our first component, app, and a few other lines of code: import react from 'react'; import logo from './logo.svg'; import './app.css'; function app() { return ( <div classname="app"> <header classname="app-header"> <img src={logo} classnam...
...ot native to javascript module syntax — it comes from webpack, the tool create-react-app uses to bundle all our javascript files together and serve them to the browser. the app component after the imports, we have a function named app. whereas most of the javascript community prefers camel-case names like helloworld, react components use pascal-case variable names, like helloworld, to make it clear that a given jsx element is a react component, and not a regular html tag. if you were to rename the app function to app, your browser would show you an error. let's look at app more closely. function app() { return ( <div classname="app"> <header classname="app-header"> <img src={logo} classname="app-logo" alt="logo" /> <p> edit <code>src/app.js</code> and...
Using the Browser API
Mozilla › Gecko › Chrome › API › Browser API › Using
end',function() { browser.findnext("forward"); }); the last event listener in this section controls what happens when the search toggle button is pressed. we switch the class values on the element to toggle the show/hide. if searchactive is true, meaning that a search has been done, we want to disable the search as we hide the search options — we disable the buttons, make searchactive false, clear the entered search value, and run htmliframeelement.clearmatch(), which gets rid of any stored/highlighted search results from the browser. searchtoggle.addeventlistener('touchend',function() { if(search.getattribute('class') === 'search') { search.setattribute('class', 'search shifted'); } else if(search.getattribute('class') === 'search shifted') { search.setattribute('class', 'sea...
...eelement.clearmatch(), which gets rid of any stored/highlighted search results from the browser. ...
Browser API
fort to cut down on domrequest usage in the browser, and remove the parts of the browser api that are no longer needed (it is used only by the firefox devtools at this point). see bug 1503070 for more details. the methods removed in firefox 65 are: htmliframeelement.addnextpaintlistener() defines a handler to listen for the next mozafterpaint event in the browser <iframe>. htmliframeelement.clearmatch() clears any content highlighted by findall() or findnext(). htmliframeelement.download() downloads a specified url, storing it at the specified filename/path. htmliframeelement.executescript() allows a specified script to be executed against a page loaded in the browser <iframe>. htmliframeelement.findall() searches for a string in a browser <iframe>'s content; if found, the first in...
...tentdimensions() retrieves the x and y dimensions of the content window. htmliframeelement.getmanifest() retrieves the manifest of an app loaded in the browser <iframe> and returns it as json. htmliframeelement.getscreenshot() takes a screenshot of the browser <iframe>'s content. this is particularly useful to get thumbnails of tabs in a tabbed browser app. htmliframeelement.purgehistory() clears all the resources (cookies, localstorage, cache, etc.) associated with the browser <iframe>. htmliframeelement.sendtouchevent() sends a touchevent to the <iframe>'s content. note that this method is available for touch enabled devices only. htmliframeelement.removenextpaintlistener() removes a handler previously set with addnextpaintlistener(). htmliframeelement.zoom() changes the zoom fac...
Activity Monitor, Battery Status Menu and top
nergy/mac-<id>.plist, where <id> can be determined with the following command. ioreg -l | grep board-id in contrast, on mac os 10.9 it is computed via a simpler machine model-independent formula that only factors in cpu usage and wakeup frequency. in both cases "energy impact" often correlates poorly with actual power consumption and should be avoided in favour of direct measurements that have clear physical meanings. what does "average energy impact" measure? when the energy tab of activity monitor is first opened, the "average energy impact" column is empty and the title bar says "activity monitor (processing...)". after 5–10 seconds, the "average energy impact" column is populated with values and the title bar changes to "activity monitor (applications in last 8 hours)". if you have t...
... application is closed, in which case it disappears immediately. and it appears that a program with an “energy impact” of roughly 20 or more will eventually show up as significant, and programs that have much higher “energy impact” values tend to show up more quickly. all of these battery status menu observations are difficult to make reliably and so should be treated with caution. it is clear, however, that the window used by the battery status menu is measured in seconds or minutes, which is much less than the 8 hour window used for “average energy impact” in activity monitor. top top is similar to activity monitor, but is a command-line utility. to see power-related measurements, invoke it as follows. top -stats pid,command,cpu,idlew,power -o power -d note: -a and -e can be...
NSS Sample Code sample2
ymmetric encryption /* example code to illustrate des enccryption/decryption using nss. * the example skips the details of obtaining the key & iv to use, and * just uses a hardcoded key & iv. * note: iv is only needed if cipher blocking chaining (cbc) mode of encryption * is used * * the recommended approach is to store and transport wrapped (encrypted) * des keys (ivs can be in the clear). however, it is a common (and dangerous) * practice to use raw des keys. this example shows the use of a raw key. */ #include "nss.h" #include "pk11pub.h" /* example key & iv */ unsigned char gkey[] = {0xe8, 0xa7, 0x7c, 0xe2, 0x05, 0x63, 0x6a, 0x31}; unsigned char giv[] = {0xe4, 0xbb, 0x3b, 0xd3, 0xc3, 0x71, 0x2e, 0x58}; int main(int argc, char **argv) { ck_mechanism_type ciphermech; ...
...buf1 len must be atleast (data len + 8) */ tmp1_outlen = tmp2_outlen = 0; /* create cipher context */ encco...
Python binding for NSS
nd_certs_from_email_addr nss.find_certs_from_nickname nss.nss_get_version nss.nss_version_check nss.set_shutdown_callback nss.get_use_pkix_for_validation nss.set_use_pkix_for_validation nss.enable_ocsp_checking nss.disable_ocsp_checking nss.set_ocsp_cache_settings nss.set_ocsp_failure_mode nss.set_ocsp_timeout nss.clear_ocsp_cache nss.set_ocsp_default_responder nss.enable_ocsp_default_responder nss.disable_ocsp_default_responder the following files were added: src/py_traceback.h doc/examples/verify_cert.py test/test_misc.py the following constants were added: nss.ku_digital_signature nss.ku_non_repudiation ...
...s 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. ...
FC_InitToken
lotid 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 password hasn't been set yet or the user forgets the...
...to reset the key database. application usage fc_inittoken() is used to reset the password for the key database when the user forgets the password. the "reset password" button of the mozilla application suite and seamonkey (in preferences->privacy & security->master passwords) calls fc_inittoken(). the "-t" (token reset) command of certutil calls fc_inittoken(). note: resetting the password clears all permanent secret and private keys. you won't be able to decrypt the data, such as mozilla's stored passwords, that were encrypted using any of those keys. see also fc_initpin, nsc_inittoken ...
NSC_InitToken
tid 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 argument. return value nsc_inittoken() returns the fol...
...ey database. examples application usage nsc_inittoken() is used to reset the password for the key database when the user forgets the password. the "reset password" button of the mozilla application suite and seamonkey (in preferences->privacy & security->master passwords) calls nsc_inittoken(). the "-t" (token reset) command of certutil calls nsc_inittoken(). note: resetting the password clears all permanent secret and private keys. you won't be able to decrypt the data, such as mozilla's stored passwords, that were encrypted using any of those keys. see also nsc_initpin, fc_inittoken ...
Utility functions
port_zfree mxr 3.2 and later rsa_formatblock mxr 3.2 and later sec_asn1decode mxr 3.4 and later sec_asn1decodeinteger mxr 3.2 and later sec_asn1decodeitem mxr 3.2 and later sec_asn1decoderabort mxr 3.9 and later sec_asn1decoderclearfilterproc mxr 3.2 and later sec_asn1decoderclearnotifyproc mxr 3.2 and later sec_asn1decoderfinish mxr 3.2 and later sec_asn1decodersetfilterproc mxr 3.2 and later sec_asn1decodersetnotifyproc mxr 3.2 and later sec_asn1decoderstart mxr 3.2 and lat...
...oderstart mxr 3.2 and later sec_asn1decoderupdate mxr 3.2 and later sec_asn1encode mxr 3.2 and later sec_asn1encodeinteger mxr 3.2 and later sec_asn1encodeitem mxr 3.2 and later sec_asn1encoderabort mxr 3.9 and later sec_asn1encoderclearnotifyproc mxr 3.2 and later sec_asn1encoderclearstreaming mxr 3.2 and later sec_asn1encodercleartakefrombuf mxr 3.2 and later sec_asn1encoderfinish mxr 3.2 and later sec_asn1encodersetnotifyproc mxr 3.2 and later sec_asn1encodersetstreaming mxr 3.
Bytecode Descriptions
ally blocks is stored in a side table, script->trynotes(). format: jof_code_offset trydestructuring no-op instruction used by the exception unwinder to determine the correct environment to unwind to when performing iteratorclose due to destructuring. this instruction must appear immediately before each jstry_destructuring span in a script's try notes. exception stack: ⇒ exception push and clear the pending exception. ┬──┬◡ノ(° -°ノ) this must be used only in the fixed sequence of instructions following a jstry_catch span (see "bytecode invariants" above), as that's the only way instructions would run with an exception pending. used to implement catch-blocks, including the implicit ones generated as part of for-of iteration. resumeindex operands: (uint24_t resumeindex) s...
...atom, jof_name, jof_checksloppy function environment setup arguments stack: ⇒ arguments create and push the arguments object for the current function activation. when it exists, arguments is stored in an ordinary local variable. jsop::arguments is used in function preludes, to populate that variable before the function body runs, not each time arguments appears in a function. if a function clearly doesn't use arguments, we optimize it away when emitting bytecode. the function's script won't use jsop::arguments at all. the current script must be a function script. this instruction must execute at most once per function activation. optimized arguments if script->needsargsobj() is false, no argumentsobject is created. instead, magicvalue(js_optimized_arguments) is pushed. this optimization ...
SpiderMonkey Internals
-stepping, step over, step out, and so on can be implemented. the debugger will have to consult jsopcode.def on its own to figure out where to plant trap instructions to implement functions like step out, but a future jsdbgapi.h will provide convenience interfaces to do these things. at most one trap per bytecode can be set. when a script (jsscript) is destroyed, all traps set in its bytecode are cleared. watchpoints, for intercepting set operations on properties and running a debugger-supplied function that receives the old value and a pointer to the new one, which it can use to modify the new value being set. line number to pc and back mapping functions. the line-to-pc direction "rounds" toward the next bytecode generated from a line greater than or equal to the input line, and may return t...
...-included if nested in addition to being directly included. jsbit.h, jslog2.cpp bit-twiddling routines. most of the work here is selectively enabling compiler-specific intrinsics such as gcc's __builtin_ctz, which is useful in calculating base-2 logarithms of integers. jsutil.cpp, jsutil.h the js_assert macro is used throughout the source as a proof device to make invariants and preconditions clear to the reader, and to hold the line during maintenance and evolution against regressions or violations of assumptions that it would be too expensive to test unconditionally at run-time. certain assertions are followed by run-time tests that cope with assertion failure, but only where i'm too smart or paranoid to believe the assertion will never fail... jsclist.h doubly-linked circular list stru...
JSAPI Cookbook
f here; for example: */ if (!js_callfunctionname(cx, global, "foo", 0, null, &r)) goto catch_block; /* instead of returning false */ if (!js_callfunctionname(cx, global, "bar", 0, null, &r)) goto catch_block; /* instead of returning false */ return true; catch_block: js::rootedvalue exc(cx); if (!js_getpendingexception(cx, &exc)) return false; js_clearpendingexception(cx); /* do error-handling stuff here */ return true; finally // javascript try { foo(); bar(); } finally { cleanup(); } if your c/c++ cleanup code doesn't call back into the jsapi, this is straightforward: /* jsapi */ bool success = false; if (!js_callfunctionname(cx, global, "foo", 0, null, &r)) goto finally_block; /* instead of returning ...
...return success; however, if cleanup() is actually a javascript function, there's a catch. when an error occurs, the jscontext's pending exception is set. if this happens in foo() or bar() in the above example, the pending exception will still be set when you call cleanup(), which would be bad. to avoid this, your jsapi code implementing the finally block must: save the old exception, if any clear the pending exception so that your cleanup code can run do your cleanup restore the old exception, if any return false if an exception occurred, so that the exception is propagated up. /* jsapi */ bool success = false; if (!js_callfunctionname(cx, global, "foo", 0, null, &r)) goto finally_block; /* instead of returning false immediately */ if (!js_callfunctionname(cx, g...
JS_GetPendingException
cx jscontext * pointer to the js context in which the exception was thrown. requires request. in a js_threadsafe build, the caller must be in a request on this jscontext. vp js::mutablehandlevalue out parameter. on success, *vp receives the current pending exception. ...
...e current pending exception. description if an exception has been thrown in the context cx, and it has not yet been caught or cleared, js_getpendingexception stores the exception object in *vp and returns true. otherwise, it returns false, and the value left in *vp is undefined. see examples in the jsapi phrasebook. ...
SpiderMonkey 1.8.7
js_newfunctionbyid body new c++ helpers while jsapi remains a c api, the engine is now implemented in c++. some c++ helpers have been introduced into the api, to help embedders writing c++ projects. please note that spidermonkey reserves the js:: namespace for itself. jsautorequest jsautosuspendrequest jsautocheckrequest jsautoentercompartment js::anchor<> js::call obsolete apis js_clearnewbornroots js_enterlocalrootscope js_leavelocalrootscope js_leavelocalrootscopewithresult js_forgetlocalroot js_newgrowablestring deleted apis js_getscopechain use js_getglobalforscopechain api changes operation callback js_setoperationcallback was introduced in js 1.8.0, replacing the branch callback, in anticipation of the addition of the tracing jit (tracemonkey). the interface was f...
...replacing the branch callback, in anticipation of the addition of the tracing jit (tracemonkey). the interface was finalized only after js 1.8.0 shipped, with bug 477187. the primary change in this interface is that it no longer counts operations; embedders are expected find another mechanism (such as a watchdog thread) to trigger regular callbacks, via js_triggeroperationcallback. regexp apis js_clearregexpstatics, js_newregexpobject, js_newregucexpobject, and js_setregexpinput now receive a pointer to the global object. this change was made in bug 571355 to move the regexp statics out of the context, to simplify cross compartment wrappers. property accessors js_propertystub, js_resolvestub, and user-defined functions of type jspropertyop (e.g. getters and setters) changed from passing jsvals ...
SpiderMonkey 45
7) js_hasownproperty (bug 1211607) js_deleteucproperty (bug 1211607) js::newfunctionfromspec (bug 1054756) js::compilefornonsyntacticscope (bug 1165486) js_checkforinterrupt (bug 1058695) js::mapdelete (bug 1159469) js::mapforeach (bug 1159469) js::newsetobject (bug 1159469) js::setsize (bug 1159469) js::sethas (bug 1159469) js::setdelete (bug 1159469) js::setadd (bug 1159469) js::setclear (bug 1159469) js::setkeys (bug 1159469) js::setvalues (bug 1159469) js::setentries (bug 1159469) js::setforeach (bug 1159469) js::exceptionstackornull (bug 814497) js::copyasyncstack (bug 1160307) js::getsavedframesource (bug 1216819) js::getsavedframeline (bug 1216819) js::getsavedframecolumn (bug 1216819) js::getsavedframefunctiondisplayname (bug 1216819) js::getsavedframeasynccause ...
...ngtracer js_ismarkinggray js_idarraylength js_idarrayget js_destroyidarray js_defaultvalue js_getparent js_setparent js::parsepropertydescriptorobject js_deleteproperty2 js_deletepropertybyid2 js_deleteucproperty2 js_deleteelement2 js_newfunctionbyid js_bindcallable js_decompilefunctionbody js_getlatin1internedstringchars js_gettwobyteinternedstringchars js_newdateobjectmsec js_cleardatecaches changed apis js_init has moved from jsapi.h to js/initialization.h js_shutdown has moved from jsapi.h to js/initialization.h js_initreflect is now implicit js_addweakpointercallback is replaced with js_addweakpointerzonegroupcallback and js_addweakpointercompartmentcallback js_removeweakpointercallback is replaced with js_removeweakpointerzonegroupcallback and js_removeweakpoin...
Shell global objects
ore 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. clearlastwarning() clear the last warning. elapsed() execution time elapsed for the current thread. decompilefunction(func) decompile a function. decompilethis() decompile the currently executing script. thisfilename() return the filename of the current script newglobal([options]) return a new global object in a new compartment. if options is given, it may have any of the following propertie...
...or will be thrown during cloning. valid keys: sharedarraybuffer. deserialize(clonebuffer) deserialize data generated by serialize. detacharraybuffer(buffer) detach the given arraybuffer object from its memory, i.e. as if it had been transferred to a webworker. helperthreadcount() returns the number of helper threads available for off-main-thread tasks. reportoutofmemory() report oom, then clear the exception and return undefined. for crash testing. throwoutofmemory() throw out of memory exception, for oom handling testing. reportlargeallocationfailure() call the large allocation failure callback, as though a large malloc call failed, then return undefined. in gecko, this sends a memory pressure notification, which can free up some memory. findpath(start, target) return an array de...
Mozilla Projects
e linguistic expression by sharpening the divide between localization and application logic. leak monitor leak monitor is a firefox extension by l. david baron that helps extension and chrome developers to find memory leaks. it will pop-up an alert when a window is closed and javascript still links to that window (for example, an observer that is not cleared when the window closes). mailnews mailnews stands for "mail and newsgroups". mailnews is the back end of the messaging parts of seamonkey and thunderbird. it provides a number of functions and capabilities, including: mccoy mccoy uses xulrunner which is bound to break, for details see this ...
... mailnews stands for "mail and newsgroups". mailnews is the back end of the messaging parts of seamonkey and thunderbird. it provides a number of functions and capabilities, including: mccoy mccoy uses xulrunner which is bound to break, for details see this post. mozilla calls mccoy a "simple system" which is a clear sign that something probably is not working, and indeed, is not. mccoy is an application that allows add-on authors to provide secure updates to their users. applications periodically look for and install updates to their add-ons. it's important that the update information retrieved has not been tampered with since being written by the add-on author. specifica...
Places Expiration
utes and uses a simple adaptive algorithm: if the last step was unable to expire enough entries the next one will expire more entries, otherwise if the previous step completed the cleanup the next step will be delayed. this ensures expiration doesn't lag behind without hitting performances when there is no need for it. apart this periodic expiration, there are other steps on idle, on shutdown on 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, l...
...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 is no need to tweak or set any preference, since adaptive behavior should satisfy each need, though in case of unexpected issues it's possibl...
XPCOM hashtable guide
...
... ...
inIDOMUtils
nged in gecko 22.0 (firefox 22.0 / thunderbird 22.0 / seamonkey 2.19) implemented by: @mozilla.org/inspector/dom-utils;1 as a service: var inidomutils = components.classes["@mozilla.org/inspector/dom-utils;1"] .getservice(components.interfaces.inidomutils); method overview void addpseudoclasslock(in nsidomelement aelement, in domstring apseudoclass); void clearpseudoclasslocks(in nsidomelement aelement); [implicit_jscontext] jsval colornametorgb(in domstring acolorname); nsiarray getbindingurls(in nsidomelement aelement); nsidomnodelist getchildrenfornode(in nsidomnode anode, in boolean ashowinganonymouscontent); unsigned long long getcontentstate(in nsidomelement aelement); void getcsspropertynames([optiona...
...ove the lock of. e.g. ":hover". haspseudoclasslock() checks whether the element element has a particular pseudo-class lock applied. boolean haspseudoclasslock( in nsidomelement aelement, in domstring apseudoclass ); parameters aelement the element to test. apseudoclass the pseudo-class lock to test for existence, e.g. ":hover". return value true if lock exists, false otherwise clearpseudoclasslocks() removes any pseudo-class locks from the element. void clearpseudoclasslocks( in nsidomelement aelement ); parameters aelement the element to remove the pseudo-class locks from. ...
nsIAccessibleSelectable
accessible/public/nsiaccessibleselectable.idlscriptable an interface for the accessibility module and in-process accessibility clients for dealing with getting and changing the selection of accessible nodes. inherits from: nsisupports last changed in gecko 1.7 method overview void addchildtoselection(in long index); void clearselection(); nsiarray getselectedchildren(); boolean ischildselected(in long index); nsiaccessible refselection(in long index); void removechildfromselection(in long index); boolean selectallselection(); attributes attribute type description selectioncount long the number of accessible children currently selected. read only. constants constant value description eselection_add 0 eselection_remove 1 eselection_getstate ...
...n_remove 1 eselection_getstate 2 methods addchildtoselection() adds the specified accessible child of the object to the object's selection. if the specified object is already selected, then it does nothing. void addchildtoselection( in long index ); parameters index the zero-based accessible child index. exceptions thrown ns_error_failure if the specified object is not selectable. clearselection() clears the selection in the object so that no children in the object are selected. void clearselection(); parameters none. getselectedchildren() returns an nsiarray of the selected nsiaccessible children. nsiarray getselectedchildren(); parameters none. return value an nsiarray. ischildselected() determines if the current child of this object is selected. boolean ischildselected( i...
nsIAnnotationService
above. note: all page annotations will get deleted when the page is removed from history if the page is not bookmarked. this means that if you create an annotation on an unvisited uri, it will get deleted when the browser shuts down. otherwise, uris can exist in history as annotations but the user has no way of knowing it, potentially violating their privacy expectations about actions such as clear history. if there is an important annotation that the user or extension wants to keep, you should add a bookmark for the page and use an expire_never annotation. this will ensure the annotation exists until the item is removed by the user. setitemannotation() this method sets an annotation for given item, overwriting any previous annotation with the same url/name. it is your job to namespace y...
...above. note: all page annotations will get deleted when the page is removed from history if the page is not bookmarked. this means that if you create an annotation on an unvisited uri, it will get deleted when the browser shuts down. otherwise, uris can exist in history as annotations but the user has no way of knowing it, potentially violating their privacy expectations about actions such as clear history. if there is an important annotation that the user or extension wants to keep, you should add a bookmark for the page and use an expire_never annotation. this will ensure the annotation exists until the item is removed by the user. setitemannotationstring() this method sets an annotation for given item by taking a string as input value, overwriting any previous annotation with the same...
nsICollection
xpcom/ds/nsicollection.idlscriptable this interface represents a list of nsisupports items. it provides basic operations on those items like: getting, setting, appending, removing, and so on. inherits from: nsiserializable last changed in gecko 1.7 method overview void appendelement(in nsisupports item); void clear(); pruint32 count(); nsienumerator enumerate(); nsisupports getelementat(in pruint32 index); void queryelementat(in pruint32 index, in nsiidref uuid, [iid_is(uuid),retval] out nsqiresult result); void removeelement(in nsisupports item); void setelementat(in pruint32 index, in nsisupports item); methods appendelement() appends a new item to the collection. void appendelement( in nsisupports...
...queryelementat(in pruint32 index, in nsiidref uuid, [iid_is(uuid),retval] out nsqiresult result); void removeelement(in nsisupports item); void setelementat(in pruint32 index, in nsisupports item); methods appendelement() appends a new item to the collection. void appendelement( in nsisupports item ) parameters item nsisupports item to be appended to the list. clear() removes all items from the collection. void clear(); parameters none. count() returns the number of items in the collection. pruint32 count(); parameters none. return value number of items in the list. enumerate() returns an nsienumerator that lets you iterate over the items in the collection. nsienumerator enumerate(); parameters none. return value an nsienumerator. getelementat() returns t...
nsICompositionStringSynthesizer
ength, compositionstringsynthesizer.attr_convertedtext); // set caret position in the composition string. (optional) compositionstringsynthesizer.setcaret("foo-bar".length, 0); // dispatch dom events to modify the focused editor compositionstringsynthesizer.dispatchevent(); when you modify the composing string, you don't need to recreate the instance anymore. the composing string information is cleared by a call of .dispatchevent(). for example, if the "bar" is converted to "bar": compositionstringsynthesizer.setstring("foo-bar-buzz"); compositionstringsynthesizer.appendclause("foo-".length, compositionstringsynthesizer.attr_convertedtext); compositionstringsynthesizer.appendclause("bar".length, compositionstringsynthesizer.attr_selectedconvertedtext); compositionstringsynthesizer.appendc...
... hasn't been called, this dispatches events to set composition string without clause information. in other words, commits composition string. if appendclause() and/or setcaret() are not called properly, e.g., sum of alength of calls of appendclause() is not same as composition string set by setstring(), this throws an exception. after a call of this, all stored composition string information is 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 ...
nsIContentViewer
playing content. inherits from: nsisupports last changed in gecko 10.0 (firefox 10.0 / thunderbird 10.0 / seamonkey 2.7) implemented by: ?????????????????????????????????????. ...
.... presshell nsipresshellptr read only. native code only! note: prior to gecko 10.0 (firefox 10.0 / thunderbird 10.0 / seamonkey 2.7), this attribute was part of nsidocumentviewer. previousviewer nsicontentviewer the previous content viewer, which has been closed but not destroyed. native code only! sticky boolean methods clearhistoryentry() clears the current history entry. this is used to clear out the saved presentation state. void clearhistoryentry(); parameters none. close() all users of a content viewer are responsible for calling both close() and destroy(), in that order. close() should be called when the load of a new page for the next content viewer begins, and destroy() should be called when the next content ...
nsIDOMNSHTMLDocument
dom/interfaces/html/nsidomnshtmldocument.idlscriptable this interface defines methods and properties supported by gecko on the document object that are not part of dom level 2. ...
...same as embeds for compatibility with netscape 4.x read only. vlinkcolor domstring same as body.vlink width long the width of the body element. read only. obsolete since gecko 6.0 methods captureevents() provided for compatibility with netscape 4.x, but does not actually do anything. void captureevents( in long eventflags ); parameters eventflags clear() used to reset a document to blank, but deprecated since gecko 1.0 and provided for compatibility with netscape 4.x; use open() and close() instead. void clear(); parameters none. execcommand() boolean execcommand( in domstring commandid, in boolean doshowui, in domstring value ); parameters commandid the name of the command to execute. see rich-text editing in mozilla for a lis...
nsIDOMStorageManager
getlocalstorageforprincipal() retur...
....org/dom/storagemanager;1 as a service: var domstoragemanager = components.classes["@mozilla.org/dom/storagemanager;1"] .getservice(components.interfaces.nsidomstoragemanager); method overview void clearofflineapps(); nsidomstorage getlocalstorageforprincipal(in nsiprincipal aprincipal, in domstring adocumenturi); long getusage(in astring aownerdomain); methods clearofflineapps() clears keys owned by offline applications. all data owned by a domain with the "offline-app" permission is removed from the database. void clearofflineapps(); parameters none. getlocalstorageforprincipal() returns the instance of the localstorage object for auri's origin. this is used to ensure that only one local storage area exists for a given origin. nsidomstorage getlocalstorage...
nsIDOMWindowUtils
provides useful dom methods and attributes. 1.0 66 introduced gecko 1.8 inherits from: nsisupports last changed in gecko 49.0 (firefox 49.0 / thunderbird 49.0 / seamonkey 2.46) implemented by: window. ...
...with loadsheet()/removesheet(). see css2 specification for details. methods activatenativemenuitemat() see nsiwidget.activatenativemenuitemat(). cannot be accessed from unprivileged context (not content-accessible) will throw a dom security error if called without universalxpconnect privileges. void activatenativemenuitemat( in astring indexstring ); parameters indexstring clearmozafterpaintevents() void clearmozafterpaintevents(); parameters none. comparecanvases() compare the two canvases, returning the number of differing pixels and the maximum difference in a channel. this will throw an error if the dimensions of the two canvases are different. this method requires universalxpconnect privileges. pruint32 comparecanvases( in nsidomhtmlcanvaselement acanvas1,...
nsIDictionary
ved in firefox 3.5; use dict.jsm instead. see bug 668424 for further information. method overview boolean haskey(in string key); void getkeys(out pruint32 count, [retval, array, size_is(count)] out string keys); nsisupports getvalue(in string key); void setvalue(in string key, in nsisupports value); nsisupports deletevalue(in string key); void clear(); methods haskey() check if a given key is present in the dictionary. boolean haskey( in string key ); parameters key key to check for. return value true if present, false if absent. getkeys() retrieve all keys in the dictionary. void getkeys( out pruint32 count, [retval, array, size_is(count)] out string keys ); return value array of all keys, unsorted. ...
... in nsisupports value ); parameters key the key by which the value can be accessed. value the value to store. deletevalue() find the value indicated by the key. nsisupports deletevalue( in string key ); parameters key the key indicating the pair to be removed. return value the removed value. if the key doesn't exist, ns_error_failure will be returned. clear() delete all key-value pairs from the dictionary. void clear(); parameters none. ...
nsIDocumentLoader
bprogresslistener notifications. inherits from: nsisupports last changed in gecko 1.8 (firefox 1.5 / thunderbird 1.5 / seamonkey 1.0) implemented by: @mozilla.org/docloaderservice;1. ...
...nly! obsolete since gecko 1.8 nsiloadgroup getloadgroup(); obsolete since gecko 1.8 boolean isbusy(); obsolete since gecko 1.8 void stop(); attributes attribute type description container nsisupports read only. documentchannel nsichannel read only. loadgroup nsiloadgroup read only. methods clearparentdocloader() obsolete since gecko 1.8 (firefox 1.5 / thunderbird 1.5 / seamonkey 1.0) void clearparentdocloader(); parameters none. createdocumentloader() obsolete since gecko 1.8 (firefox 1.5 / thunderbird 1.5 / seamonkey 1.0) void createdocumentloader( out nsidocumentloader aninstance ); parameters aninstance destroy() ...
nsIEditorSpellCheck
checkcurrentword( in wstring suggestedword ); parameters suggestedword missing description return value true if the specified word is misspelled; otherwise false. checkcurrentwordnosuggest() like checkcurrentword(), checks the word you give it, returning true if it is misspelled. this is faster than checkcurrentword() because it does not compute any suggestions. note: this does not clear any suggestions left over from previous calls to checkcurrentword(), so there may be suggestions, but they will be invalid. boolean checkcurrentwordnosuggest( in wstring suggestedword ); parameters suggestedword the word to check. return value true if the word is misspelled; otherwise false. getcurrentdictionary() returns the name of the dictionary currently in use. astring getcurren...
...ters 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 selected language as the default for future use. if you have called canspellcheck() but not initspellchecker(), you can still call this function to clear the cached spell check object, and no preferences are saved. void uninitspellchecker(); parameters none. updatecurrentdictionary() updates the dictionary in use to be sure it corresponds to what the editor needs. void updatecurrentdictionary(); parameters none. remarks prior to gecko 9.0 (firefox 9.0 / thunderbird 9.0 / seamonkey 2.6), this method took one parameter, a reference to the nsiedito...
nsIHttpChannel
exceptions thrown ns_error_failure if called during visitrequestheaders(). setrequestheader() this method is called to set the value of a particular request header. this method allows, for example, the cookies module to add "cookie" headers to the outgoing http request. this method may only be called before the channel is opened. if avalue is empty and amerge is false, the header will be cleared. void setrequestheader( in acstring aheader, in acstring avalue, in boolean amerge ); parameters aheader the case-insensitive name of the request header to query (for example "cookie"). avalue the request header value to set (for example "x=1"). amerge if true, the new header value will be merged with any existing values for the specified header. this flag is ignored if the spe...
...s thrown ns_error_in_progress if called after the channel has been opened. ns_error_failure if called during visitrequestheaders(). setresponseheader() set the value of a particular response header. this method allows, for example, the html content sink to inform the http channel about http-equiv headers found in html <meta> tags. if value is empty and merge is false, the header will be cleared. void setresponseheader( in acstring header, in acstring value, in boolean merge ); parameters header the case-insensitive name of the response header to set(for example "cache-cookie"). value the response header value to set (for example "no-cache"). merge if true, the new header value will be merged with any existing values for the specified header. this flag is ignored if th...
nsIMsgAccount
nsimsgaccount mailnews/base/public/nsimsgaccount.idlscriptable an account consists of an incoming server and one or more outgoing identities. inherits from: nsisupports last changed in gecko 1.7 method overview void addidentity(in nsimsgidentity identity); void clearallvalues(); void init(); void removeidentity(in nsimsgidentity identity); astring tostring(); attributes attribute type description defaultidentity nsimsgidentity identities nsisupportsarray read only. outgoing identity list (array of nsimsgidentity's) incomingserver nsimsgincomingserver incoming server stuff key acstring internal key identifying itself methods addidentity() adds a new identity to this account. void addidentity( in nsimsgidentity identity ); parameters identity the ...
...cription defaultidentity nsimsgidentity identities nsisupportsarray read only. outgoing identity list (array of nsimsgidentity's) incomingserver nsimsgincomingserver incoming server stuff key acstring internal key identifying itself methods addidentity() adds a new identity to this account. void addidentity( in nsimsgidentity identity ); parameters identity the identity to add. clearallvalues() clear all user preferences associated with an account. void clearallvalues(); parameters none. init() initializes an account. void init(); parameters none. exceptions thrown ns_error_already_opened if it is called more then once removeidentity() removes an identity from this account. void removeidentity( in nsimsgidentity identity ); parameters identity the identity to remov...
nsIMsgDBHdr
interface is usually given to you in return to a query from the message database. there are utility functions that also return it though. for instance, msghdrforcurrentmessage() will return the currently selected message's header. headers are backed by the database: a call to these functions directly modifies the state of the database, although it is not saved until the database is committed. in clear, if you want to do a persistent change to a message header, such as marking it as read, or replied to, or whatever, you must do it through its corresponding nsimsgfolder (msghdr.folder) or nsimsgdatabase (msghdr.folder.msgdatabase). it is also mandatory to set msghdr.folder.msgdatabase = null after performing this kind of operations to prevent leaking. don't even think about using orflags and/or ...
...ring() void setprioritystring(in string priority); parameters priority string describing the priority. orflags() unsigned long orflags(in unsigned long flags); parameters flags flags to be added to the current message flags. andflags() unsigned long andflags(in unsigned long flags); parameters flags flags to be retained on the current message flags. all other flags are cleared. setreferences() void setreferences(in string references); parameters references sets the list of references for a news message. getstringreference() returns one of the references in the list of references. acstring getstringreference(in long refnum); parameters refnum the index of the reference to return. must be less than the total number of references. setrecipientsarr...
nsIMsgIdentity
the nsimsgidentity interface contains all the personal outgoing mail information for a given person. each identity is identified by a key, which is the id string in the identity preferences, such as in mail.identity.<id>.replyto. ...
... boolean readonly: default request for return receipt option for this identity. if this is set, the return receipt menu item on the compose window will be checked. receiptheadertype long readonly: requestdsn boolean readonly: default request for dsn option for this identity. if this is set, the dsn menu item on the compose window will be checked. methods clearallvalues() note: this is really dangerous! this destroys all pref values; do not call this unless you know what you're doing! void clearallvalues(); parameters none. copy() copy the attributes of the identity we pass in. void copy(in nsimsgidentity identity); parameters identity getunicharattribute() getter for unicode attributes. note: these attributes persist across sessions. ...
nsIMsgSearchSession
in nsmsgsearchattribvalue attrib, in nsmsgsearchopvalue op, in nsimsgsearchvalue value); long countsearchscopes(); void getnthsearchscope(in long which,out nsmsgsearchscopevalue scopeid, out nsimsgfolder folder); void addscopeterm(in nsmsgsearchscopevalue scope, in nsimsgfolder folder); void adddirectoryscopeterm(in nsmsgsearchscopevalue scope); void clearscopes(); [noscript] boolean scopeusescustomheaders(in nsmsgsearchscopevalue scope, in voidptr selection, in boolean forfilters); boolean isstringattribute(in nsmsgsearchattribvalue attrib); void addallscopes(in nsmsgsearchscopevalue attrib); void search(in nsimsgwindow awindow); void interruptsearch(); void pausesearch(); void resumes...
...simsgfolder folder); parameters which return values scopeid folder addscopeterm() add a scope (e.g. a mail folder) to the search. void addscopeterm(in nsmsgsearchscopevalue scope, in nsimsgfolder folder); parameters scope folder adddirectoryscopeterm() void adddirectoryscopeterm(in nsmsgsearchscopevalue scope); parameters scope clearscopes() void clearscopes(); scopeusescustomheaders() call this function everytime the scope changes! it informs the fe if the current scope support custom header use. fes should not display the custom header dialog if custom headers are not supported. [noscript] boolean scopeusescustomheaders(in nsmsgsearchscopevalue scope, in voidptr selection, ...
nsIMsgWindowCommands
c/nsimsgwindow.idlscriptable this interface defines methods used by the back end to update the user interface in a mail or news message list. inherits from: nsisupports last changed in gecko 1.9 (firefox 3) the javascript implementation of this used by thunderbird is given here. method overview void selectfolder(in acstring folderuri); void selectmessage(in acstring messageuri); void clearmsgpane(); methods selectfolder() this method is called by the backend to change the folder displayed in the message window. this could be as a result of clicking on a new mail alert, or by clicking a link to a newsgroup. void selectfolder( in acstring folderuri ); parameters folderuri the uri of the folder to select. selectmessage() this method is called by the backend to change the displ...
... link to a newsgroup. void selectfolder( in acstring folderuri ); parameters folderuri the uri of the folder to select. selectmessage() this method is called by the backend to change the displayed message. for instance, when deleting attachments, this causes the message to be redisplayed. void selectmessage( in acstring messageuri ); parameters messageuri the uri of the message to open. clearmsgpane() this method is called by the backend when it wants to clear the message pane, for instance if you select the group header . void clearmsgpane(); paramters none. ...
nsIMutableArray
rtelementat() is never used, and null elements are never explicitly added to the array, then it is guaranteed that nsiarray.queryelementat() will never return a null value. any of these methods may throw ns_error_out_of_memory when the array must grow to complete the call, but the allocation fails. method overview void appendelement(in nsisupports element, in boolean weak); void clear(); void insertelementat(in nsisupports element, in unsigned long index, in boolean weak); void removeelementat(in unsigned long index); void replaceelementat(in nsisupports element, in unsigned long index, in boolean weak); methods appendelement() append an element at the end of the array. void appendelement( in nsisupports element, in boolean weak ); parame...
... methods appendelement() append an element at the end of the array. void appendelement( in nsisupports element, in boolean weak ); parameters element the element to append. weak whether or not to store the element using a weak reference. exceptions thrown ns_error_failure when a weak reference is requested, but the element does not support nsiweakreference. clear() clear the entire array, releasing all stored objects. void clear(); parameters none. insertelementat() insert an element at the given position, moving the element currently located in that position, and all elements in higher position, up by one. void insertelementat( in nsisupports element, in unsigned long index, in boolean weak ); parameters element the element to insert. ...
nsINavBookmarkObserver
nged. this should be one of the nsinavbookmarksservice.type constants. aparentid the id of the folder containing the item. aguid the unique id associated with the item. aparentguid the unique id associated with the item's parent. notes this table indicates what anewvalue should be depending on property specified by aproperty: property string value "cleartime" empty string; this property means the history was deleted, so there's no last visit date. "title" the new title for the item "favicon" the "moz-anno" url for the new favicon image. "uri" the new uri for the item. "tags" empty string; this property indicates that the set of tags for the item have changed. "dateadded" the prtime at...
...m 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, in long long avisitid, in prtime atime, in unsigned long at...
nsIPermissionManager
the subject is null. see also nsisimpleenumerator ...
...otification; one notification will be broadcast for each change, and will involve a single permission. data : "deleted" a permission was deleted. the subject is the deleted nsipermission. data : "added" a permission was added. the subject is the added nsipermission. data : "changed" a permission was changed. the subject is the new nsipermission. data : "cleared" the entire permission list was cleared. the subject is null. see also nsisimpleenumerator ...
Component; nsIPrefBranch
his object is created with the root "browser.startup.", the preferences "browser.startup.page", "browser.startup.homepage", and "browser.startup.homepage_override" can be accessed by simply passing "page", "homepage", or "homepage_override" to the various get/set methods. ...
...s. the structure of aobserver is any object with an observe function. see nsiobserver and here is a quick snippet: var myobserver = { observe: function(asubject, atopic, adata) { //do stuff here } } aholdweak true holds a weak reference to aobserver. the object must implement the nsisupportsweakreference interface or this will fail. false holds a strong reference to aobserver. clearuserpref() called to clear a user set value from a specific preference. this will, in effect, reset the value to the default value. if no default value exists the preference will cease to exist. note: this method does nothing if the prefbranch it is called on is a default branch. void clearuserpref( in string aprefname ); parameters aprefname the preference to be cleared. remarks no...
nsIPromptService
var prompts = components.classes["@mozilla.org/embedcomp/prompt-service;1"] .getservice(components.interfaces.nsipromptservice); var result = prompts.confirm(null, "title of this dialog", "are you sure?"); // result is now true if ok was clicked, and false if cancel was clicked confirmcheck example confirmchec...
... confirmex example confirmex displays a dialog with up to 3 buttons and an optional checkbox. var prompts = components.classes["@mozilla.org/embedcomp/prompt-service;1"] .getservice(components.interfaces.nsipromptservice); var check = {value: false}; // default the checkbox to false ...
nsISmsDatabaseService
abody a domstring containing the body t...
...equest. processid optional a number representing the id of the process. getnextmessageinlist() void getnextmessageinlist( in long listid, in long requestid, [optional] in unsigned long long processid ); parameters listid a number representing the id of the message list. requestid a number representing the id of the request. processid optional a number representing the id of the process. clearmessagelist() void getnextmessageinlist( in long listid, ); parameters listid a number representing the id of the message list. markmessageread() requires gecko 15.0(firefox 15.0 / thunderbird 15.0 / seamonkey 2.12) void markmessageread( in long messageid, in boolean value, in long requestid, [optional] in unsigned long long processid ); parameters messageid a number repre...
nsITextInputProcessor
n(), and setcaretinpendingcomposition() on the focused editor. if appendclausetopendingcomposition() and/or setcaretinpendingcomposition() are not called properly, e.g., sum of alength of calls of appendclausetopendingcomposition() is not same as composition string set by setpendingcompositionstring(), this throws an exception. after a call of this, the pending composition string information is cleared. therefore, you can set new composition string continuously. boolean flushpendingcomposition(in nsidomkeyevent adomkeyevent optional, in unsigned long akeyflags optional); parameters adomkeyevent optional when the modifying composition is caused by a key operation, this should be specified. if this is specified, keyboard events may be dispatched when gecko ...
...er state on of this affects other instances. therefore, this is useful if you want to create textinputprocessor instance in every dom window or something. see also sharing modifier state during multiple instances. void sharemodifierstateof(in nsitextinputprocessor aother); parameters aother another instance. if this is null, the instance stops sharing modifier state with other instances and clears all modifier state. startcomposition() this starts composition explicitly. this is useful if your ime doesn't generate composing string but provides some ui to select commit string. if the instance has a composition already, this throws an exception. boolean startcomposition(in nsidomkeyevent adomkeyevent optional, in unsigned long akeyflags optional); parameters ...
nsITransactionManager
editor/txmgr/idl/nsitransactionmanager.idlscriptable this interface is implemented by an object that wants to manage/track transactions. ...
...dd. beginbatch() turns on the transaction manager's batch mode, forcing all transactions executed by the transaction manager's dotransaction() method to be aggregated together until endbatch() is called. this mode allows an application to execute and group together several independent transactions so they can be undone with a single call to undotransaction(). void beginbatch(); parameters none. clear() clears the undo and redo stacks. void clear(); parameters none. dotransaction() calls a transaction's nsitransaction.dotransaction() method, then pushes it on the undo stack. this method calls the transaction's nsitransaction.addref() method. the transaction's nsitransaction.release() method will be called when the undo or redo stack is pruned or when the transaction manager is destroyed. void...
nsIXmlRpcClient
ing: this interface was removed from firefox 3 and is no longer available. extensions/xml-rpc/idl/nsixmlrpcclient.idlscriptable please add a summary to this article. ...
...rs 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 asked to authenticate password password to be used if asked to authenticate clearauthentication() clear authentication info void setauthentication ( in string username, in string password ) ; parameters username password setencoding() set character encoding. the default charset if this function is not called is "utf-8" void setauthentication ( in string encoding ) ; parameters encoding encoding charset to be used asynccall() call remote method m...
Getting Started Guide
pply * 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. nscomptr is defined in the source files: xpcom/base/nscomptr.h xpcom/base/nscomptr.cpp ...though you probably don't want to look in there, just yet. with nscomptr, you can write code that is shorter, cleaner, clearer, and safer, than you can with raw xpcom interface pointers. xpcom basics: ownership and reference counting this is a quick refresher on some fundamental issues of xpcom. you should already know this, and should be able to just skim this short section. if this is unfamiliar material, you're not ready for nscomptrs yet. a good place to learn about the basic rules and reasoning behind com is in ...
...it's very easy to forget to release at the appropriate moment. or to addref too many or too few times. how does nscomptr help? nscomptr manages addref, release, and other red-tape for you. an nscomptr looks and acts as much like a raw xpcom interface pointer as c allows, but it knows it owns the object it points to. this takes a little getting used to on your part, but ends up with less typing, clearer, safer code, and less leaks. for instance, here is a typical snippet of code (at its most compact) where you assign a xpcom interface pointer into a member variable, i.e., the body of a `setter' function, side-by-side using raw xpcom interface pointers and nscomptrs. comparison 1. setting a member variable. // raw xpcom interface pointers... // given: |nsifoo* mfooptr;| /* ...
Reference Manual
into routines for use as "out" parameters. the problem is that inside the getter there is no knowledge of nscomptrs. it thinks it's getting a pointer (or a reference) to a raw xpcom interface pointer. nscomptrs smart assignment operators will not be called. the old value, if any, will be leaked. this is where the getter_addrefs( nscomptr& ) comes in. getter_addrefs releases the old value, if any, clears it out, and returns a pointer to it, allowing the getter to fill in your nscomptr with a new addrefed value. we use getter_addrefs as a sort of replacement for the & that we would apply to a raw xpcom interface pointer in these situations. getter_addrefs packages up all the magic we normally get from nscomptrs constructors and assignment operators. // raw xpcom interface...
...you've written 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...
Using the clipboard
from text to images. create a transferring object. this object can be the component @mozilla.org/widget/transferable;1 which implements the interface nsitransferable. initialize the transferring object with the nsiloadcontext obtained from the window that is the source of the clipboard data. this ensures that if the copied data comes from a window in private browsing mode, the clipboard will be cleared when private browsing mode ends. for reading from the clipboard you can call the init method of the transferable with null as nsiloadcontext, but you have to call it. tell the transferring object about the type of data being copied. tell the transferring object about the data to copy. create a clipboard object which refers to the system clipboard. tell the clipboard object to copy the data ...
...e"); // we multiply the length of the string by 2, since it's stored in 2-byte utf-16 // format internally. trans.settransferdata("text/unicode", supportsstring(str), str.length * 2); the first line gets the transferring component which implements nsitransferable. next we need to initialize it with a "privacy context", which will ensure that source data from inside private browsing mode will be cleared when the mode is exited. please note: the sourcewindow variable is a placeholder for whatever window owns the data being copied -- from any dom element you can obtain it via element.ownerdocument.defaultview. if, and only if, you are placing data on the clipboard that is unrelated to web content the user is viewing, you can pass a null privacy context to the init method. the next step is to te...
wrappedJSObject
: comp.hello is not a function this happens because, as we mentioned earlier, comp is not the helloworld js object itself, but an xpconnect wrapper around it: > dump(comp); [xpconnect wrapped nsisupports] the idea of these wrappers is to make the javascript-implemented xpcom components look just like any other xpcom component to the user. this also makes the public interface of the component clearer and provides protection for the component's internal data. calling queryinterface on the wrapper works, because it is defined in the nsisupports interface, and the wrapper knows the underlying object implements nsisupports: > comp.queryinterface(components.interfaces.nsihelloworld); [xpconnect wrapped (nsisupports, nsihelloworld)] as you can see, the queryinterface call also made the wrappe...
...ryinterface(components.interfaces.nsihelloworld); [xpconnect wrapped (nsisupports, nsihelloworld)] as you can see, the queryinterface call also made the wrapper know about the other interface our component supports. assuming the nsihelloworld interface defines the hello method, we can now call it: > comp.hello() hello world! while this behavior is nice for production code as it forces you to clearly define the interfaces that should be used to access the component, it's inconvenient to write the interfaces (and recompile each time you change them) when working on a prototype of the component. meet wrappedjsobject xpconnect lets you bypass its wrappers and access the underlying js object directly using the wrapper.wrappedjsobject property if the wrapped object allows this. more specifica...
Debugger - Firefox Developer Tools
s), thereby escaping the capability-based limits. for this reason, addallglobalsasdebuggees is only available to privileged code. removedebuggee(global) remove the global object designated byglobal from this debugger instance’s set of debuggees. return undefined. this method interpretsglobal using the same rules that adddebuggee does. removing a global as a debuggee from this debugger clears all breakpoints that belong to that debugger in that global. removealldebuggees() remove all the global objects from this debugger instance’s set of debuggees. return undefined. hasdebuggee(global) return true if the global object designated byglobal is a debuggee of this debugger instance. this method interpretsglobal using the same rules that adddebuggee does. getdebuggees() ...
... 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 their handler. note that, if breakpoints using other handler objects are set at the same location(s) ashandler, they remain in place. clearallbreakpoints() remove all breakpoints set using this debugger instance. findallglobals() return an array of debugger.object instances referring to all the globa...
Debugger.Object - Firefox Developer Tools
watchpoint handler calls are cross-compartment, intra-thread calls: the call takes place in the same thread that changed the property, and inhandler's method's compartment (typically the same as the debugger's compartment). the new watchpoint belongs to the debugger instance to which this debugger.object instance belongs; disabling the debugger instance disables this watchpoint. clearobjectwatchpoint()(future plan) remove any object watchpoint set on the referent. setpropertywatchpoint(name,handler)(future plan) set a watchpoint on the referent's property namedname, reporting events by callinghandler's methods. any previous watchpoint handler on this property for this debugger.object instance is replaced. ifhandler is null, the property is no longer watched.handler is...
...re plan) set a watchpoint on the referent's property namedname, reporting events by callinghandler's methods. any previous watchpoint handler on this property for this debugger.object instance is replaced. ifhandler is null, the property is no longer watched.handler is as described for debugger.object.prototype.setobjectwatchpoint, except that it does not receive extensionsprevented events. clearpropertywatchpoint(name)(future plan) remove any watchpoint set on the referent's property namedname. unwrap() if the referent is a wrapper that this debugger.object's compartment is permitted to unwrap, return a debugger.object instance referring to the wrapped object. if we are not permitted to unwrap the referent, return null. if the referent is not a wrapper, return this debugger.obje...
All keyboard shortcuts - Firefox Developer Tools
dcrumbs bar right arrow right arrow right arrow focus the html pane shift + tab shift + tab shift + tab focus the css pane tab tab tab css pane these shortcuts work when you're in the inspector's css pane. ...
...lose 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 ctrl + f open the object inspector pane ctrl + click ctrl + click ctrl + click clear the object inspector pane esc esc esc focus on the command line ctrl + shift + k cmd + opt + k ctrl + shift + k clear output ctrl + shift + l ctrl + l from firefox 67: cmd + k ctrl + shift + l command line interpreter these shortcuts apply when you're in the command line interpreter. command win...
Network monitor toolbar - Firefox Developer Tools
a box enabling you to filter requests by url and by properties. ...
...request blocking an array of buttons to filter the network request list by type: by the content type of the response xhr requests websocket upgrades and messages (labeled ws) other requests a checkbox that allows you to disable caching. throttling menu, to simulate various connection types a menu of other actions: persist logs: by default, the network monitor is cleared each time you navigate to a new page or reload the current page. when you select persist logs, the log is not cleared on page load. import har imports a har (http archive) file. save all as har opens a file dialog box so you can save the current contents of the network log as a har file with the extension .har. copy all as har copies the current contents of the network log to the clipb...
Network request list - Firefox Developer Tools
the request list of the network monitor shows a list of all the network requests made in the course of loading the page. network request list by default, the network monitor shows a list of all the network requests made in the course of loading the page. each request is displayed in its own row: by default, the network monitor is cleared each time you navigate to a new page or reload the current page. you can override this behavior by checking "enable persistent logs" in the settings. network request columns you can toggle columns on and off by right-clicking on the table header and choosing the specific column from the context menu. a reset columns command is available on the context menu to reset the columns to their initial configuration. you can also change the width of the columns t...
... field displays the requests that contain that string in the request or response headers or in the content of the response. you can expand each item to show the specific item that matches the string. clicking an item in the search results highlights that item in the monitor list, and displays the corresponding information in the request details pane. other ways to use the search panel: to clear the search string: click the x icon in the search field. to make the search case sensitive: click the case sensitive (aa) icon next to the search field. to close the search panel, do one of the following: click the x icon next to the search field. click the search icon in the network monitor toolbar. context menu context-clicking on a row in the list displays a context menu wit...
Settings - Firefox Developer Tools
select element" button. the "select element" button is now always shown. themes this enables you to choose one of two themes. there's a light theme, which is the default: a dark theme: common preferences settings that apply to more than one tool. there's just one of these: enable persistent logs a setting to control whether or not the web console and network monitor clear their output when you navigate to a new page. if common preferences is not included in the settings, web console logs can be persisted by using the 'about:config' url in browser address bar, searching for: 'devtools.webconsole.persistlog' then toggling this value to true inspector show browser styles a setting to control whether styles applied by the browser (user-agent styles) should...
... first-load performance in all tabs that have the toolbox open. this setting persists, meaning that if it is set, caching will be disabled whenever you reopen the devtools. caching is re-enabled when the devtools are closed. note that service workers are not affected by this option. note that this option was called "disable cache" in firefox versions previous to 49, but it was renamed to make it clearer that this affects the http cache, and not service workers/the cache api. disable javascript reload the current tab with javascript disabled. enable service workers over http enable service worker registrations from insecure websites. enable browser chrome and add-on debugging toolboxes enable you to use developer tools in the context of the browser itself, and not only web content. ena...
Web console keyboard shortcuts - Firefox Developer Tools
command windows macos linux scroll to start of console output (only if the comm...
... command windows macos linux scroll to start of console output (only if the command line is empty) home home home scroll to end of co...
Web Console UI Tour - Firefox Developer Tools
the web console's interface is split into three horizontal sections, detailed in the sections below. toolbar the toolbar across the top contains a number of features: garbage can: click this icon to clear the contents of the console. funnel: click this icon to filter the messages that are displayed in the console. filter categories: you can click a filter category (such as errors, warnings, css, or xhr) to display just those types of messages. settings ("gear" menu): new in firefox 71, you can click the gear icon to access the new settings menu, where you can toggle the following features on and off: persist logs: when enabled, the console doesn't clear on page reload, or new page load. show timestamps: when enabled, timestamps are shown on the left-hand side of each messag...
...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, and linux) or cmd + k on macos. command line the command line starts with double angle brackets (>>). use it to enter javascript expressions. in firefox 71 onwards, there is a new "split pane" icon on the right hand side of the command line — clicking this will open the new console multi-line mode...
Background Tasks API - Web APIs
left. as a result, while our shim doesn't constrain itself to the amount of idle time left in the current event loop pass like the true requestidlecallback(), it does at least limit the callback to no more than 50 milliseconds of run time per pass. the implementation of our shim for cancelidlecallback() is much simpler: window.cancelidlecallback = window.cancelidlecallback || function(id) { cleartimeout(id); } if cancelidlecallback() isn't defined, this creates one which simply passes the specified callback id through to cleartimeout(). now your code will work even on browsers that don't support the background tasks api, albeit not as efficiently. interfaces the background tasks api adds only one new interface: idledeadline an object of this type is passed to the idle callback to ...
...ce in the article. window.requestidlecallback = window.requestidlecallback || function(handler) { let starttime = date.now(); return settimeout(function() { handler({ didtimeout: false, timeremaining: function() { return math.max(0, 50.0 - (date.now() - starttime)); } }); }, 1); }; window.cancelidlecallback = window.cancelidlecallback || function(id) { cleartimeout(id); }; managing the task queue next, let's look at the way we manage the tasks that need to be performed. we're going to do this by creating a fifo queue of tasks, which we'll run as time allows during the idle callback period. enqueueing tasks first, we need a function that enqueues tasks for future execution. that function, enqueuetask(), looks like this: function enqueuetask(tas...
Compositing and clipping - Web APIs
s more than adequate for most situations, but it limits the order in which composite shapes are built. we can, however, change this behaviour by setting the globalcompositeoperation property. in addition, the clip property allows us to hide unwanted parts of shapes. globalcompositeoperation we can not only draw new shapes behind existing shapes but we can also use it to mask off certain areas, clear sections from the canvas (not limited to rectangles like the clearrect() method does) and more. globalcompositeoperation = type this sets the type of compositing operation to apply when drawing new shapes, where type is a string identifying which of the twelve compositing operations to use. see compositing examples for the code of the following examples. clipping paths a clipping path i...
...hen translate the origin to the center. next, we create the circular clipping path by drawing an arc and calling clip(). clipping paths are also part of the canvas save state. if we wanted to keep the original clipping path we could have saved the canvas state before creating the new one. everything that's drawn after creating the clipping path will only appear inside that path. you can see this clearly in the linear gradient that's drawn next. after this a set of 50 randomly positioned and scaled stars is drawn, using the custom drawstar() function. again the stars only appear inside the defined clipping path. screenshotlive sample « previousnext » ...
console - Web APIs
Web › API › Console
d to open the specified link") this page documents the methods available on the console object and gives a few usage examples. note: this feature is available in web workers. note: the actual console interface is defined as all lower case (i.e. not console), for historical reasons. methods console.assert() log a message and stack trace to console if the first argument is false. console.clear() clear the console. console.count() log the number of times this line has been called with the given label. console.countreset() resets the value of the counter with the given label. console.debug() outputs a message to the console with the log level debug. console.dir() displays an interactive listing of the properties of a specified javascript object. this listing lets you use disclos...
... 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 float color cursor display font and its longhand equivalents line-height margin outline and its longhand equivalents padding text-* properties such as text-transform white-space word-spacing and word-break writing-mode note: the console message behaves like an inline element by default. to see the effects of padding, margin, etc. you should set it to for example display: inline...
Constraint validation API - Web APIs
ation api enables checking values that users have entered into form controls, before submitting the values to the server. 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. even though client-side validation can prevent many common kinds of invalid values, invalid ones can still be sent by older browsers or by attackers trying to trick your web application. the...
...it fires an invalid event at the element, returns false, and then reports the validity status to the user in whatever way the user agent has available. otherwise, it returns true. setcustomvalidity(message) sets a custom error message string to be shown to the user upon submitting the form, explaining why the value is not valid — when a message is set, the validity state is set to invalid. to clear this state, invoke the function with an empty string passed as its argument. in this case the custom error message is cleared, the element is considered valid, and no message is shown. examples take the following form: <form> <label for="name">enter username (upper and lowercase letters): </label> <input type="text" name="name" id="name" required pattern="[a-za-z]+"> <button>submit</but...
DataTransferItemList.DataTransferItem() - Web APIs
) { // drag data item is uri data[i].getasstring(function (s){ console.log("... ...
...data[i].getasstring(function (s){ console.log("... ...
DataTransferItemList.length - Web APIs
) { // drag data item is uri data[i].getasstring(function (s){ console.log("... ...
...data[i].getasstring(function (s){ console.log("... ...
DataTransferItemList.remove() - Web APIs
console.log("... ...
... s); }); } } } function dragover_handler(ev) { console.log("dragover"); ev.preventdefault(); // set the dropeffect to move ev.datatransfer.dropeffect = "move" } function dragend_handler(ev) { console.log("dragend"); var datalist = ev.datatransfer.items; for (var i = 0; i < datalist.length; i++) { datalist.remove(i); } // clear any remaining drag data datalist.clear(); } html <h1>example uses of <code>datatransferitemlist</code> methods and property</h1> <div> <p id="source" ondragstart="dragstart_handler(event);" ondragend="dragend_handler(event);" draggable="true"> select this element, drag it to the drop zone and then release the selection to move the element.</p> </div> <div id="target" ondrop="drop_handler(event);" ondragover="dragover_ha...
Element: compositionend event - Web APIs
vent.data}`); }); live example html <div class="control"> <label for="name">on macos, click in the textbox below,<br> then type <kbd>option</kbd> + <kbd>`</kbd>, then <kbd>a</kbd>:</label> <input type="text" id="example" name="example"> </div> <div class="event-log"> <label>event log:</label> <textarea readonly class="event-log-contents" rows="8" cols="25"></textarea> <button class="clear-log">clear</button> </div> css body { padding: .2rem; display: grid; grid-template-areas: "control log"; } .control { grid-area: control; } .event-log { grid-area: log; } .event-log-contents { resize: none; } label, button { display: block; } input[type="text"] { margin: .5rem 0; } kbd { border-radius: 3px; padding: 1px 2px 0; border: 1px solid black; } js cons...
...{ grid-area: control; } .event-log { grid-area: log; } .event-log-contents { resize: none; } label, button { display: block; } input[type="text"] { margin: .5rem 0; } kbd { border-radius: 3px; padding: 1px 2px 0; border: 1px solid black; } js const inputelement = document.queryselector('input[type="text"]'); const log = document.queryselector('.event-log-contents'); const clearlog = document.queryselector('.clear-log'); clearlog.addeventlistener('click', () => { log.textcontent = ''; }); function handleevent(event) { log.textcontent = log.textcontent + `${event.type}: ${event.data}\n`; } inputelement.addeventlistener('compositionstart', handleevent); inputelement.addeventlistener('compositionupdate', handleevent); inputelement.addeventlistener('compositionend...
Element: compositionstart event - Web APIs
vent.data}`); }); live example html <div class="control"> <label for="name">on macos, click in the textbox below,<br> then type <kbd>option</kbd> + <kbd>`</kbd>, then <kbd>a</kbd>:</label> <input type="text" id="example" name="example"> </div> <div class="event-log"> <label>event log:</label> <textarea readonly class="event-log-contents" rows="8" cols="25"></textarea> <button class="clear-log">clear</button> </div> css body { padding: .2rem; display: grid; grid-template-areas: "control log"; } .control { grid-area: control; } .event-log { grid-area: log; } .event-log-contents { resize: none; } label, button { display: block; } input[type="text"] { margin: .5rem 0; } kbd { border-radius: 3px; padding: 1px 2px 0; border: 1px solid black; } js cons...
...{ grid-area: control; } .event-log { grid-area: log; } .event-log-contents { resize: none; } label, button { display: block; } input[type="text"] { margin: .5rem 0; } kbd { border-radius: 3px; padding: 1px 2px 0; border: 1px solid black; } js const inputelement = document.queryselector('input[type="text"]'); const log = document.queryselector('.event-log-contents'); const clearlog = document.queryselector('.clear-log'); clearlog.addeventlistener('click', () => { log.textcontent = ''; }); function handleevent(event) { log.textcontent = log.textcontent + `${event.type}: ${event.data}\n`; } inputelement.addeventlistener('compositionstart', handleevent); inputelement.addeventlistener('compositionupdate', handleevent); inputelement.addeventlistener('compositionend...
Element: compositionupdate event - Web APIs
vent.data}`); }); live example html <div class="control"> <label for="name">on macos, click in the textbox below,<br> then type <kbd>option</kbd> + <kbd>`</kbd>, then <kbd>a</kbd>:</label> <input type="text" id="example" name="example"> </div> <div class="event-log"> <label>event log:</label> <textarea readonly class="event-log-contents" rows="8" cols="25"></textarea> <button class="clear-log">clear</button> </div> css body { padding: .2rem; display: grid; grid-template-areas: "control log"; } .control { grid-area: control; } .event-log { grid-area: log; } .event-log-contents { resize: none; } label, button { display: block; } input[type="text"] { margin: .5rem 0; } kbd { border-radius: 3px; padding: 1px 2px 0; border: 1px solid black; } js cons...
...{ grid-area: control; } .event-log { grid-area: log; } .event-log-contents { resize: none; } label, button { display: block; } input[type="text"] { margin: .5rem 0; } kbd { border-radius: 3px; padding: 1px 2px 0; border: 1px solid black; } js const inputelement = document.queryselector('input[type="text"]'); const log = document.queryselector('.event-log-contents'); const clearlog = document.queryselector('.clear-log'); clearlog.addeventlistener('click', () => { log.textcontent = ''; }); function handleevent(event) { log.textcontent = log.textcontent + `${event.type}: ${event.data}\n`; } inputelement.addeventlistener('compositionstart', handleevent); inputelement.addeventlistener('compositionupdate', handleevent); inputelement.addeventlistener('compositionend...
EventTarget.addEventListener() - Web APIs
: function eventhandler(event) { if (event.type == 'fullscreenchange') { /* handle a full screen toggle */ } else /* fullscreenerror */ { /* handle a full screen toggle error */ } } safely detecting option support in older versions of the dom specification, the third parameter of addeventlistener() was a boolean value indicating whether or not to use capture. over time, it became clear that more options were needed. rather than adding more parameters to the function (complicating things enormously when dealing with optional values), the third parameter was changed to an object that can contain various properties defining the values of options to configure the process of removing the event listener. because older browsers (as well as some not-too-old browsers) still assume the ...
...hen called, `this` will refer to the global object --> ... </table> the value of this within logid() is a reference to the global object window (or undefined in the case of strict mode. specifying "this" using bind() the function.prototype.bind() method lets you specify the value that should be used as this for all calls to a given function. this lets you easily bypass problems where it's unclear what this will be, depending on the context from which your function was called. note, however, that you'll need to keep a reference to the listener around so you can remove it later. this is an example with and without bind(): const something = function(element) { // |this| is a newly created object this.name = 'something good'; this.onclick1 = function(event) { console.log(this.name...
Using the Gamepad API - Web APIs
ferently here. instead of constantly storing the gamepad's latest state in a variable it only stores a snapshot, so to do the same thing in chrome you have to keep polling it and then only use the gamepad object in code when it is available. we have done this below using window.setinterval(); once the object is available the gamepad info is outputted, the game loop is started, and the interval is cleared using window.clearinterval(). note that in older versions of chrome navigator.getgamepads() is implemented with a webkit prefix. we attempt to detect and handle both the prefixed version and the standard version of the function for backwards compatibility. var interval; if (!('ongamepadconnected' in window)) { // no gamepad events available, poll instead. interval = setinterval(pollgamepa...
...avigator.getgamepads ? navigator.getgamepads() : (navigator.webkitgetgamepads ? navigator.webkitgetgamepads : []); for (var i = 0; i < gamepads.length; i++) { var gp = gamepads[i]; if (gp) { gamepadinfo.innerhtml = "gamepad connected at index " + gp.index + ": " + gp.id + ". it has " + gp.buttons.length + " buttons and " + gp.axes.length + " axes."; gameloop(); clearinterval(interval); } } } now on to the main game loop. in each execution of the loop we check if one of four buttons is being pressed; if so, we update the values of the a and b movement variables appropriately, then update the left and top properties, changing their values to the current values of a and b respectively. this has the effect of moving the ball around the screen. in current ...
Geolocation.watchPosition() - Web APIs
at takes a geolocationposition object as an input parameter. error optional an optional callback function that takes a geolocationpositionerror object as an input parameter. options optional an optional positionoptions object that provides configuration options for the location watch. return value an integer id that identifies the registered handler. ...
...return value an integer id that identifies the registered handler. the id can be passed to the geolocation.clearwatch() to unregister the handler. ...
IDBObjectStore - Web APIs
ction object to which this object store belongs. idbobjectstore.autoincrement read only the value of the auto increment flag for this object store. methods idbobjectstore.add() returns an idbrequest object, and, in a separate thread, creates a structured clone of the value, and stores the cloned value in the object store. this is for adding new records to an object store. idbobjectstore.clear() creates and immediately returns an idbrequest object, and clears this object store in a separate thread. this is for deleting all current records out of an object store. idbobjectstore.count() returns an idbrequest object, and, in a separate thread, returns the total number of records that match the provided key or idbkeyrange. if no arguments are provided, it returns the total number of rec...
...pera android full support 14safari ios full support 8samsung internet android full support 1.5 full support 1.5 no support 1.5 — 7.0prefixed prefixed implemented with the vendor prefix: webkitclearchrome full support 24 full support 24 no support 23 — 57prefixed prefixed implemented with the vendor prefix: webkitedge full support 12firefox full support 16 full support ...
MediaPositionState.position - Web APIs
, uses setinterval() to establish a callback which fires once per second to refresh the position information by calling setpositionstate(). if the media is still playing when the interval is fired, setpositionstate() is called with an object that specifies the duration, playback rate, and position as reported by a mymedia object that describes the track being played. ...
...rack being played. if the media is not playing, clearinterval() is used to remove the interval handler. let positioninterval = window.setinterval(() => { if (mymedia.isplaying) { navigator.mediasession.setpositionstate({ duration: mymedia.trackdurationinseconds, playbackrate: mymedia.playbackrate, position: mymedia.trackplaypositioninseconds }); } else { window.clearinterval(positioninterval); } }, 1000); specifications specification status comment media session standardthe definition of 'mediapositionstate.position' in that specification. draft initial definition. ...
PaymentRequest.abort() - Web APIs
the paymentrequest.abort() method of the paymentrequest interface causes the user agent to end the payment request and to remove any user interface that might be shown. syntax paymentrequest.abort(); returns void. parameters none examples the following example sets up a timeout to clear the payment request that might have been abandoned or neglected. ...
...d the payment request and to remove any user interface that might be shown. syntax paymentrequest.abort(); returns void. parameters none examples the following example sets up a timeout to clear the payment request that might have been abandoned or neglected. ...
Performance API - Web APIs
e getentries(), getentriesbytype(), and getentriesbyname() methods on the performance interface. performance timeline level 2 candidate recommendation adds serializer to the performanceentry interface as well as adding the performanceobserver interface and callback resource timing level 1 candidate recommendation adds the performanceresourcetiming interface. adds the clearresourcetimings() method, the setresourcetimingbuffersize() method, and the onresourcetimingbufferfull event handler to the performance interface. also adds the timing-allow-origin response header. resource timing level 2 working draft adds the nexthopprotocol, workerstart, transfersize, encodedbodysize, and decodedbodysize properties to the performanceresourcetiming interface. ...
...nt handler to the performance interface. also adds the timing-allow-origin response header. resource timing level 2 working draft adds the nexthopprotocol, workerstart, transfersize, encodedbodysize, and decodedbodysize properties to the performanceresourcetiming interface. resource timing level 3 editor's draft user timing recommendation adds mark(), clearmarks(), measure() and clearmeasures() methods to the performance interface. adds the performancemark and peformancemeasure interfaces. user timing level 2 working draft implementation status as shown in the performance interface's browser compatibility table, most of these interfaces are broadly implemented by desktop browsers. to test your browser's support for the perfo...
Using the Screen Capture API - Web APIs
a mediastream whose contents are taken from a user-selected area of the screen. startcapture() is called when the "start capture" button is clicked. async function startcapture() { logelem.innerhtml = ""; try { videoelem.srcobject = await navigator.mediadevices.getdisplaymedia(displaymediaoptions); dumpoptionsinfo(); } catch(err) { console.error("error: " + err); } } after clearing the contents of the log in order to get rid of any leftover text from the previous attempt to connect, startcapture() calls getdisplaymedia(), passing into it the constraints object defined by displaymediaoptions. using await, the following line of code does not get executed until after the promise returned by getdisplaymedia() resolves. upon resolution, the promise returns a mediastream, whic...
...g the screen capture api in an <iframe>, the <iframe> element's allow attribute. ...
User Timing API - Web APIs
trytype, thus set entrytype to "mark" to get all marks (and set name accordingly to retrieve more specific entries). performance.getentriesbytype(entrytype) returns all performance entries in the performance timeline with the specified entrytype, thus set entrytype to "mark" to get all marks. removing performance marks to remove a specific mark from the performance timeline, call performance.clearmarks(name) where name is the name of the mark(s) you want removed. if this method is called with no arguments, all mark type entries will be removed from the performance timeline. performance measures measure events are also named by the application but they are placed between two marks thus they are effectively a midpoint between two marks. creating a performance measure a measure is created...
...entrytype to "measure" to get all measures (and set name accordingly to retrieve more specific entries). performance.getentriesbytype(entrytype) returns all performance entries in the performance timeline with the specified entrytype, thus set entrytype to "measure" to get all measures. removing performance measures to remove a specific measure from the performance timeline, call performance.clearmeasures(name) where name is the name of the measure(s) you want removed. if this method is called with no arguments, all measure type entries will be removed from the performance timeline. interoperability as shown in the performance interface's browser compatibility table, the user timing methods are broadly implemented by desktop and mobile browsers (the only exceptions are desktop safari an...
Hello GLSL - Web APIs
« previousnext » ...
... « previousnext » ...
Hello vertex attributes - Web APIs
« previousnext » ...
... « previousnext » ...
Textures from code - Web APIs
« previousnext » ...
... « previousnext » ...
WebGL by example - Web APIs
explanations about the examples are found in both the main text and in comments within the code. you should read all comments, because more advanced examples could not repeat comments about parts of the code that were previously explained. getting to know the rendering context detect webgl this example demonstrates how to detect a webgl rendering context and reports the result to the user. clearing with colors how to clear the rendering context with a solid color. clearing by clicking how to combine user interaction with graphics operations. clearing the rendering context with a random color when the user clicks. simple color animation a very basic color animation, done by clearing the webgl drawing buffer with a different random color every second. color masking modifying random ...
...and webgl the example explores the effect of setting (or not setting) the canvas size to its element size in css pixels, as it appears in the browser window. boilerplate 1 the example describes repeated pieces of code that will be hidden from now on, as well as defining a javascript utility function to make webgl initialization easier. scissor animation some animation fun with scissoring and clearing operations. raining rectangles a simple game that demonstrates clearing with solid colors, scissoring, animation, and user interaction. shader programming basics hello glsl a very basic shader program that draws a solid color square. hello vertex attributes combining shader programming and user interaction through vertex attributes. textures from code a simple demonstration of pr...
Getting started with WebGL - Web APIs
the webgl context and start rendering content. // // start here // function main() { const canvas = document.queryselector("#glcanvas"); // initialize the gl context const gl = canvas.getcontext("webgl"); // only continue if webgl is available and working if (gl === null) { alert("unable to initialize webgl. your browser or machine may not support it."); return; } // set clear color to black, fully opaque gl.clearcolor(0.0, 0.0, 0.0, 1.0); // clear the color buffer with specified clear color gl.clear(gl.color_buffer_bit); } window.onload = main; the first thing we do here is obtain a reference to the canvas, assigning it to a variable named canvas. once we have the canvas, we try to get a webglrenderingcontext for it by calling getcontext() and passing it th...
...g it to a variable named canvas. once we have the canvas, we try to get a webglrenderingcontext for it by calling getcontext() and passing it the string "webgl". if the browser does not support webgl, getcontext() will return null in which case we display a message to the user and exit. if the context is successfully initialized, the variable gl is our reference to it. in this case, we set the clear color to black, and clear the context to that color (redrawing the canvas with the background color). at this point, you have enough code that the webgl context should successfully initialize, and you should wind up with a big black, empty box, ready and waiting to receive content. view the complete code | open this demo on a new page ...
Fundamentals of WebXR - Web APIs
sed frameworks and libraries are available to make it much easier to deal with all of that. how is webxr different from webvr? webvr was generally considered to be an experimental api designed to help specification writers determine the best approaches to creating an api for virtual reality on the web. as browser developers built support for webvr and allowed developers to experiment, it became clear that in order to finish an api for virtual environments on the web, it would make more sense to start a new specification than to try to "fix" webvr. thus, webxr was created. the most obvious difference, at the highest level, is that webxr supports not just virtual reality applications, but also augmented reality, which blends virtual objects with the user's true physical environment. another k...
...ing for the kind of session you want to create. virtual reality in a vr environment, the entire image is digitally created by your app or site, from foreground objects all the way to the background or skybox. your frame drawing code will have to redraw every pixel of each view during each frame in order to avoid the potential of artifacts being left behind. some platforms may provide previously-cleared frames to you, while others may optimize performance by not erasing the framebuffers in order to avoid having to touch each pixel twice per frame. there are two vr session modes available in webxr: inline and immersive. the former, specified by the session mode string inline, presents the rendered scene within the context of a document in a web browser, and doesn't require special xr hardware ...
Movement, orientation, and motion: A WebXR example - Web APIs
stedrefspace = xrreferencespace; let pose = null; animationframerequestid = session.requestanimationframe(drawframe); adjustedrefspace = applyviewercontrols(xrreferencespace); pose = frame.getviewerpose(adjustedrefspace); if (pose) { let gllayer = session.renderstate.baselayer; gl.bindframebuffer(gl.framebuffer, gllayer.framebuffer); logglerror("bindframebuffer"); gl.clearcolor(0, 0, 0, 1.0); gl.cleardepth(1.0); // clear everything gl.clear(gl.color_buffer_bit | gl.depth_buffer_bit); logglerror("glclear"); const deltatime = (time - lastframetime) * 0.001; // convert to seconds lastframetime = time; for (let view of pose.views) { let viewport = gllayer.getviewport(view); gl.viewport(viewport.x, viewport.y, viewp...
...et the xrviewerpose representing the viewer's point of view—for both of their eyes. if that's successful, we begin preparing to render by getting the xrwebgllayer being used by the session and binding its frame buffer to be used as the webgl frame buffer (so that rendering webgl draws into the layer and therefore the xr device's display). with webgl now configured to render to the xr device, we clear the frame to black and are ready to begin rendering. the time elapsed since the last frame was rendered (in seconds) is computed by subtracting the previous frame's timestamp, lastframetime, from the current time as specified by the time parameter and then multiplying by 0.001 to convert milliseconds to seconds. the current time is then saved into lastframetime; the drawscene() function ends by...
Using the Web Speech API - Web APIs
and therefore recommended. speechrecognition.interimresults: defines whether the speech recognition system should return interim results, or just final results. final results are good enough for this simple demo. speechrecognition.maxalternatives: sets the number of alternative potential matches that should be returned per result. this can sometimes be useful, say if a result is not completely clear and you want to display a list if alternatives for the user to choose the correct one from. but it is not needed for this simple demo, so we are just specifying one (which is actually the default anyway.) recognition.grammars = speechrecognitionlist; recognition.continuous = false; recognition.lang = 'en-us'; recognition.interimresults = false; recognition.maxalternatives = 1; starting the spe...
...pulated with <option>s via javascript (see later on.) <h1>speech synthesiser</h1> <p>enter some text in the input below and press return to hear it. change voices using the dropdown menu.</p> <form> <input type="text" class="txt"> <div> <label for="rate">rate</label><input type="range" min="0.5" max="2" value="1" step="0.1" id="rate"> <div class="rate-value">1</div> <div class="clearfix"></div> </div> <div> <label for="pitch">pitch</label><input type="range" min="0" max="2" value="1" step="0.1" id="pitch"> <div class="pitch-value">1</div> <div class="clearfix"></div> </div> <select> </select> </form> javascript let's investigate the javascript that powers this app. setting variables first of all, we capture references to all the dom elements involve...
Window.localStorage - Web APIs
the read-only localstorage property allows you to access a storage object for the document's origin; the stored data is saved across browser sessions. localstorage is similar to sessionstorage, except that while data stored in localstorage has no expiration time, data stored in sessionstorage gets cleared when the page session ends — that is, when the page is closed. (data in a localstorage object created in a "private browsing" or "incognito" session is cleared when the last "private" tab is closed.) data stored in either localstorage is specific to the protocol of the page. in particular, data stored by a script on a site accessed with http (e.g., http://example.com) is put in a different localstorage object from the same site accessed with https (e.g., https://example.com). the keys and...
...in's local storage object and adds a data item to it using storage.setitem(). localstorage.setitem('mycat', 'tom'); the syntax for reading the localstorage item is as follows: const cat = localstorage.getitem('mycat'); the syntax for removing the localstorage item is as follows: localstorage.removeitem('mycat'); the syntax for removing all the localstorage items is as follows: localstorage.clear(); note: please refer to the using the web storage api article for a full example. specifications specification status comment html living standardthe definition of 'localstorage' in that specification. living standard ...
window.location - Web APIs
Web › API › Window › location
> </body> </html> …the same thing but with an animated page scroll: var showbookmark = (function () { var _usehash, _scrollx, _scrolly, _nodex, _nodey, _itframe, _scrollid = -1, _bookmark, /* * nduration: the duration in milliseconds of each frame * nframes: number of frames for each scroll */ nduration = 200, nframes = 10; function _next () { if (_itframe > nframes) { clearinterval(_scrollid); _scrollid = -1; return; } _isbot = true; document.documentelement.scrolltop = math.round(_scrolly + (_nodey - _scrolly) * _itframe / nframes); document.documentelement.scrollleft = math.round(_scrollx + (_nodex - _scrollx) * _itframe / nframes); if (_usehash && _itframe === nframes) { location.hash = _bookmark; } _itframe++; } function _chkowner () { if (_isbo...
... = true; document.documentelement.scrolltop = math.round(_scrolly + (_nodey - _scrolly) * _itframe / nframes); document.documentelement.scrollleft = math.round(_scrollx + (_nodex - _scrollx) * _itframe / nframes); if (_usehash && _itframe === nframes) { location.hash = _bookmark; } _itframe++; } function _chkowner () { if (_isbot) { _isbot = false; return; } if (_scrollid > -1) { clearinterval(_scrollid); _scrollid = -1; } } if (window.addeventlistener) { window.addeventlistener("scroll", _chkowner, false); } else if (window.attachevent) { window.attachevent("onscroll", _chkowner); } return function (sbookmark, busehash) { var onode = document.queryselector(sbookmark); _scrolly = document.documentelement.scrolltop; _scrollx = document.documentelement.scrolllef...
Window - Web APIs
Web › API › Window
methods from windoworworkerglobalscope and eventtarget. window.alert() displays an alert dialog. window.blur() sets focus away from the window. window.cancelanimationframe() enables you to cancel a callback previously scheduled with window.requestanimationframe. window.cancelidlecallback() enables you to cancel a callback previously scheduled with window.requestidlecallback. window.clearimmediate() cancels the repeated execution set using setimmediate. window.close() closes the current window. window.confirm() displays a dialog with a message that the user needs to respond to. window.dump() writes a message to the console. window.find() searches for a given string in a window. window.focus() sets focus on the current window. window.getcomputedstyle() gets computed ...
...here eventtarget.addeventlistener() register an event handler to a specific event type on the window. eventtarget.dispatchevent() used to trigger an event. windoworworkerglobalscope.atob() decodes a string of data which has been encoded using base-64 encoding. windoworworkerglobalscope.btoa() creates a base-64 encoded ascii string from a string of binary data. windoworworkerglobalscope.clearinterval() cancels the repeated execution set using windoworworkerglobalscope.setinterval(). windoworworkerglobalscope.cleartimeout() cancels the delayed execution set using windoworworkerglobalscope.settimeout(). windoworworkerglobalscope.createimagebitmap() accepts a variety of different image sources, and returns a promise which resolves to an imagebitmap. optionally the source is cropped ...
XRWebGLLayer.framebuffer - Web APIs
nspected or changed. calling functions such as framebuffertexture2d(), framebufferrenderbuffer(), deleteframebuffer(), or getframebufferattachmentparameter() on an opaque framebuffer results in the webgl error invalid_operation (0x0502). opaque framebuffers are considered incomplete and are not available for rendering other than while executing the requestanimationframe() callback. attempting to clear, draw to, or read from the framebuffer results in a webgl invalid_framebuffer_operation error (0x0506). calling checkframebufferstatus() on the webgl context from outside the animation frame callback causes the webgl framebuffer_unsupported error (0x8cdd) to be reported. opaque framebuffers initialized with the depth property set to false will not have a depth buffer and will rely on the coordin...
...iedalpha context attribute is set. note: the depth and stencil properties are not required to be supported in order for a browser to be construed as having full webgl support. the default configuration of a new framebuffer upon creating a new xrwebgllayer, its new framebuffer is initialized just like the default framebuffer for any webgl interface: the color buffer is configured with its clear value set to the color (0, 0, 0, 0) (meaning transparent black). the depth buffer's clear value is the number 1.0. the stencil buffer is filled with 0. examples this example gets the xrwebgllayer for a session and then passes its framebuffer into the webgl context's bindframebuffer() function. let gllayer = xrsession.renderstate.baselayer; gl.bindframebuffer(gl.framebuffer, gllayer.framebuf...
ARIA annotations - Accessibility
reserve more complex semantics that go beyond a simple text string. a basic description simple descriptions basically just involve usage of aria-description on an element to provide a description that can’t be gotten from the element’s text alone. ...
...mple text string. a basic description simple descriptions basically just involve usage of aria-description on an element to provide a description that can’t be gotten from the element’s text alone. ...
Implementing a Microsoft Active Accessibility (MSAA) Server - Accessibility
olutions: assistive technology vendors need some things which msaa does not provide, such as: no way of signifying that a document has finished loading. fire event_object_statechange for a window/client/pane object when it starts to load a new document. use state_busy to indicate that a new document is being loaded. when the loading has finished, fire another event_object_statechange event and clear the state_busy flag. no method to get clipped/unclipped bounds of a piece of text within a text object. this is needed by screen magnifiers. no scrollto method, also needed by screen magnifiers. implement a custom interface for text objects, and support it through queryinterface or queryservice if it's being implemented on a different object than iaccessible is. support a scrollto method which t...
...rnet explorer uses role_text without state_readonly and role_text with state_readonly for ordinary web page text. however, it uses role_statictext for labels. solution: use role_statictext for labels specific to dialog and ui controls, and always use role_text for document text even if the text is not editable (in that case use role_text with state_readonly). use role_text with the readonly flag cleared for editable text fields. issues with links problem: some assistive technologies have inflexible heuristics when it comes to reading links. they may not read the object unless the states are correctly set. second, they can mishandle the object if it cannot parse the whitespace according to its own rules. most assistive techologies don't know what to do with links embedded in a dialog, as is b...
Perceivable - Accessibility
lationship made between content—can also be determined programmatically, or be inferred from text description. the main situations in which this is relevant are: text labels and the form elements they describe. these are associated unambiguously using the <label> element, which can be picked up by screenreaders, etc. image alt text. content images should have text available that clearly describes the image's contents, which can be programmatically associated with it (e.g., alt text), or otherwise is easy to associate (e.g., describes it and is sat right next to it). this should mean that the full meaning can still be inferred even if you can't see the image. lists. if the order of list items is important, use an ordered list (<ol>). the whole of html: a go...
...o html: a good basis for accessibility. 1.3.3 sensory characteristics (a) instructions for operating controls or understanding content do not rely on a single sense. this may prove inaccessible to people with a disability related to that sense, or a device that does not support that sense. so, for example: "click the round button to continue" the button should be clearly labelled so that it is obvious that it is the button you need to press. if there are multiple buttons, make sure they are all clearly labelled to distinguish their function. "listen to the audio instructions for guidance" this is obviously problematic—audio will be inaccessible to those with hearing impairments, whereas text can be read, but also spoken by a screenreader if require...
Understandable - Accessibility
assistance: help users avoid and correct mistakes this guideline centers around helping users enter correct information when required with the minimum of mistakes. success criteria how to conform to the criteria practical resource 3.3.1 error identification (a) when a user is filling out a form or choosing between options, any error that is detected should be clearly reported to the user, along with the form control that the error relates to. it is advisable to implement client-side error detection and handling, via html5 form validation features, and/or javascript, whatever is best for your situation. when an error is detected, an intuitive error message should be shown next to the form input that is at fault to help the user correct their inputs. for...
... note: server-side validation should *always* be used alongside client-side validation. client-side validation is too easy to turn off or otherwise get around, so it can't be relied on alone. see form data validation for comprehensive validation information, and wai-aria: dynamic content updates for information on live regions. 3.3.2 labels or instructions (a) clear instructions should be provided when data input is required. when a simple instruction or prompt is required, you can use <label> elements for single inputs like name or age, a combination or <label>s and <fieldset>s/<legend>s for multiple inputs that go together (like the elements of a date of birth or postal address). when more complex explanation is required, you can always include explan...
Mastering margin collapsing - CSS: Cascading Style Sheets
into a single margin whose size is the largest of the individual margins (or just one of them, if they are equal), a behavior known as margin collapsing. note that the margins of floating and absolutely positioned elements never collapse. ...
...g. note that the margins of floating and absolutely positioned elements never collapse. margin collapsing occurs in three basic cases: adjacent siblings the margins of adjacent siblings are collapsed (except when the latter sibling needs to be cleared past floats). no content separating parent and descendants if there is no border, padding, inline part, block formatting context created, or clearance to separate the margin-top of a block from the margin-top of one or more of its descendant blocks; or no border, padding, inline content, height, min-height, or max-height to separate the margin-bottom of a block from the margin-bottom of one or more of its descendant blocks, then those margins collapse. the collapsed margin ends up outside the parent. empty blocks if there is no border, pa...
Relationship of flexbox to other layout methods - CSS: Cascading Style Sheets
a flex item. for example, if an item is floated and then its parent becomes a flex container. or, how a flex container behaves as part of layout. an element set to display: flex behaves in most ways like any other block level container that establishes a containing block. floats will not intrude, and the containers' margins will not collapse. with regard to flex items, if an item was floated or cleared and then becomes a flex item due to the parent having display: flex applied, the floating and clearing will no longer happen, and the item will not be taken out of normal flow in the way that floats are. if you have used the vertical-align property, as used with inline-block or table layout for alignment, this will no longer affect the item and you can use the alignment properties of flexbox in...
...ve used the vertical-align property, as used with inline-block or table layout for alignment, this will no longer affect the item and you can use the alignment properties of flexbox instead. in this next live example the child elements have been floated, and then their container has had display: flex added. if you remove display: flex, you should see that the .box element collapses as we have no clearing applied. this demonstrates that the float is happening. re-apply display: flex and the collapsing does not happen. this is because the items no longer have a float applied, as they have been transformed into flex items. flexbox and grid layout css grid layout and flexbox generally act in the same way with regards to overwriting other methods. you might however want to use flexbox as a fall...
CSS Grid Layout and Progressive Enhancement - CSS: Cascading Style Sheets
i am using floats for older browsers and grid for new ones.</div>...
... just as if you had wrapped them in a div or other element set to display: table. if you have an item set to display: table-cell, and then in a feature query change the parent to display: grid, this anonymous box creation will not happen. this means you can overwrite display: table based layouts, without having additional anonymous boxes. floated elements as we have already seen, float and also clear have no effect on a grid item. therefore you do not need to explicitly set items to float: none. vertical alignment the alignment property vertical-align has no effect on a grid item. in layouts using display: inline-block or display: table, you might use the vertical-align property to perform basic alignment. in your grid layout you then have the far more powerful box alignment properties. mu...
Recipe: Media objects - CSS: Cascading Style Sheets
e sullivan it refers to a two-column box with an image on one side and descriptive text on the other, e.g. a facebook post or tweet. requirements media object pattern needs some or all of the following characteristics: stacked on mobile, two columns on desktop. the image can be on the left or right. the image might be small or large. media objects can be nested. the media object should clear the contents no matter which side is tallest. the recipe download this example choices made i have chosen to use grid layout for the media object as it allows me to control the layout in two dimensions when i need to. this means that when we have a footer, with short content above, the footer can be pushed down to the bottom of the media object. another reason to use grid layout is in o...
...which defines a flipped grid template causing the layout to be mirrored. when we nest one media object inside another we need to place it into the second track in the regular layout, and the first track when flipped. fallbacks there are a number of possible fallbacks for this pattern, depending on the browsers you wish to support. a good catch-all would be to float the image left, and to add a clearfix to the box to ensure that it contained the floats. download this example once floated elements become grid items the float no longer applies so you don’t need to do anything special to clear the float. what you will need to do is remove any margins applied to the item, and any widths which we don’t need in a grid context (we have the gap property to control it in grids, and the trac...
Cubic Bezier Generator - CSS: Cascading Style Sheets
h.round(result) == result ? ...
... ? ...
float - CSS: Cascading Style Sheets
Web › CSS › float
tional squares would continue to stack to the right, until they filled the containing box, after which they would wrap to the next line. a floated element is at least as tall as it's tallest nested floated children. we gave the parent width: 100% and floated it to ensure it is tall enough to encompass it's floated children, and to make sure it takes up the width of the parent so we don't have to clear it's adjacent sibling. html <section> <div class="left">1</div> <div class="left">2</div> <div class="right">3</div> <p>lorem ipsum dolor sit amet, consectetur adipiscing elit. morbi tristique sapien ac erat tincidunt, sit amet dignissim lectus vulputate. donec id iaculis velit. aliquam vel malesuada erat. praesent non magna ac massa aliquet tincidunt vel in massa. p...
...lit. aliquam vel malesuada erat. praesent non magna ac massa aliquet tincidunt vel in massa. phasellus feugiat est vel leo finibus congue.</p> </section> css section { border: 1px solid blue; width: 100%; float: left; } div { margin: 5px; width: 50px; height: 150px; } .left { float: left; background: pink; } .right { float: right; background: cyan; } result clearing floats sometimes you may want to force an item to move below any floated elements. for instance, you may want paragraphs to remain adjacent to floats, but force headings to be on their own line. see clear for examples. specifications specification status comment css logical properties and values level 1the definition of 'float and clear' in that specification. ...
Block formatting context - Developer guides
l containers (elements where column-count or column-width isn't auto, including elements with column-count: 1). column-span: all should always create a new formatting context, even when the column-span: all element isn't contained by a multicol container (spec change, chrome bug). formatting contexts affect layout, but typically, we create a new block formatting context for the positioning and clearing floats rather than changing the layout, because an element that establishes a new block formatting context will: contain internal floats. exclude external floats. suppress margin collapsing. note: a flex/grid container(display: flex/grid/inline-flex/inline-grid) establishes a new flex/grid formatting context, which is similar to block formatting context except layout. there's no floati...
... red; } specifications specification status comment css display module level 3the definition of 'block formatting context' in that specification. candidate recommendation define bfc(abbr) etc. css level 2 (revision 1)the definition of 'block formatting context' in that specification. recommendation initial definition. see also float, clear css key concepts: css syntax, at-rule, comments, specificity and inheritance, the box, layout modes and visual formatting models, and margin collapsing, or the initial, computed, resolved, specified, used, and actual values. definitions of value syntax, shorthand properties and replaced elements. ...
Challenge solutions - Developer guides
s. solution add lines to modify the margin-left property. be sure to specify it as marginleft in javascript. ...
...margin-left property. be sure to specify it as marginleft in javascript. ...
HTML attribute reference - HTML: Hypertext Markup Language
, you read or set values of the desired type, so input.maxlength is always going to return a number and when you set input.maxlength, it wants a number. if you pass another type, it is automatically converted to a number as specified by the standard javascript rules for type conversion. idl attributes can reflect other types such as unsigned long, urls, booleans, etc. unfortunately, there are no clear rules and the way idl attributes behave in conjunction with their corresponding content attributes depends on the attribute. most of the time, it will follow the rules laid out in the specification, but sometimes it doesn't. html specifications try to make this as developer-friendly as possible, but for various reasons (mostly historical), some attributes behave oddly (select.size, for example) a...
...ding or trailing whitespace. the following examples are valid ways to mark up a boolean attribute: <div itemscope> this is valid html but invalid xml. </div> <div itemscope=itemscope> this is also valid html but invalid xml. </div> <div itemscope=""> this is valid html and also valid xml. </div> <div itemscope="itemscope"> this is also valid html and xml, but perhaps a bit verbose. </div> to be clear, the values "true" and "false" are not allowed on boolean attributes. to represent a false value, the attribute has to be omitted altogether. this restriction clears up some common misunderstandings: with checked="false" for example, the element’s checked attribute would be interpreted as true because the attribute is present. ...
<input type="week"> - HTML: Hypertext Markup Language
Web › HTML › Element › input › week
o browser; cross-browser support is currently a bit limited, with only chrome/opera and microsoft edge supporting it at this time. in non-supporting browsers, the control degrades gracefully to function identically to <input type="text">. in chrome/opera the week control provides slots to fill in week and year values, a pop-up calendar interface to select them more visually, and an "x" button to clear the control's value. the edge week control is somewhat more elaborate, opening up week and year pickers with sliding reels. value a domstring representing a week and year, or empty events change and input supported common attributes autocomplete, list, readonly, and step idl attributes value, valueasdate, valueasnumber, and list. meth...
...ers in the positive direction when there are two equally close options. for week inputs, the value of step is given in weeks, with a scaling factor of 604,800,000 (since the underlying numeric value is in milliseconds). the default value of step is 1, indicating 1week. the default stepping base is -259,200,000, which is the beginning of the first week of 1970 ("1970-w01"). at this time, it's unclear what a value of "any" means for step when used with week inputs. this will be updated as soon as that information is determined. using week inputs week inputs sound convenient at first glance, since they provide an easy ui for choosing weeks, and they normalize the data format sent to the server, regardless of the user's browser or locale. however, there are issues with <input type="week"> beca...
<input>: The Input (Form Input) element - HTML: Hypertext Markup Language
Web › HTML › Element › input
name="range" min="0" max="25"/> html5 reset a button that resets the contents of the form to default values. not recommended. <input type="reset" name="reset"/> search a single-line text field for entering search strings. line-breaks are automatically removed from the input value. may include a delete icon in supporting browsers that can be used to clear the field. displays a search icon instead of enter key on some devices with dynamic keypads. <input type="search" name="search"/> html5 submit a button that submits the form. <input type="submit" name="submit"/> tel a control for entering a telephone number. displays a telephone keypad in some devices with dynamic keypads. <input ty...
...r control conditions. as web developers, it's important that we never assume that people will know all the things that we know. the diversity of people using the web—and by extension your web site—practically guarantees that some of your site's visitors will have some variation in thought processes and/or circumstances that leads them to interpret your forms very differently from you without clear and properly-presented labels. placeholders are not accessible the placeholder attribute lets you specify a text that appears within the <input> element's content area itself when empty. the placeholder should never be required in order to understand your forms. it is not a label, and should not be used as a substitute, because it isn't. the placeholder is used to show an example input, not an ...
HTTP Index - HTTP
Web › HTTP › Index
header. 67 cache-control cache-control, general header, http, http header, reference the cache-control general-header field is used to specify directives for caching mechanisms in both requests and responses. caching directives are unidirectional, meaning that a given directive in a request is not implying that the same directive is to be given in the response. 68 clear-site-data http, http header, reference, header the clear-site-data header clears browsing data (cookies, storage, cache) associated with the requesting website. it allows web developers to have more control over the data stored locally by a browser for their origins. 69 connection http, headers, reference, web the connection general header controls whether or not th...
...se code indicates that the request has succeeded, but that the client doesn't need to go away from its current page. a 204 response is cacheable by default. an etag header is included in such a response. 226 205 reset content http, http status code, reference, status code the http 205 reset content response status tells the client to reset the document view, so for example to clear the content of a form, reset a canvas state, or to refresh the ui. 227 206 partial content http, http status, range requests, success the http 206 partial content success status response code indicates that the request has succeeded and has the body contains the requested ranges of data, as described in the range header of the request. 228 300 multiple choices ...
WeakMap - JavaScript
ps! ...
...azerty" wm2.get(o2); // undefined, because there is no key for o2 on wm2 wm2.get(o3); // undefined, because that is the set value wm1.has(o2); // true wm2.has(o2); // false wm2.has(o3); // true (even if the value itself is 'undefined') wm3.set(o1, 37); wm3.get(o1); // 37 wm1.has(o1); // true wm1.delete(o1); wm1.has(o1); // false implementing a weakmap-like class with a .clear() method class clearableweakmap { constructor(init) { this._wm = new weakmap(init); } clear() { this._wm = new weakmap(); } delete(k) { return this._wm.delete(k); } get(k) { return this._wm.get(k); } has(k) { return this._wm.has(k); } set(k, v) { this._wm.set(k, v); return this; } } specifications specification ecmascript (ecma-262)the defin...
WeakRef - JavaScript
ining and improving how it works.) 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...
... ...
Image file type and format guide - Web media technologies
design. although svg support is good, it may be worth offering a png fallback for older browsers. best choice fallback svg, lossless webp, or png png screenshots unless you're willing to compromise on quality, you should use a lossless format for screenshots. this is particularly important if there's any text in your screenshot, as text easily becomes fuzzy and unclear under lossy compression. png is probably your best bet, but lossless webp is arguably going to be better compressed. best choice fallback lossless webp or png; jpeg if compression artifacts aren't a concern png or jpeg; gif for screenshots with low color counts diagrams, drawings, and charts for any image that can be represented using vector graphics, svg...
...n png or jpeg; gif for screenshots with low color counts diagrams, drawings, and charts for any image that can be represented using vector graphics, svg is the best choice. otherwise, you should use a lossless format like png. if you do choose a lossy format, such as jpeg or lossy webp, carefully weigh the compression level to avoid causing text or other shapes to become fuzzy or unclear. best choice fallback svg png providing image fallbacks while the standard html <img> element doesn't support compatibility fallbacks for images, the <picture> element does. <picture> is used as a wrapper for a number of <source> elements, each specifying a version of the image in a different format or under different media conditions, as well as an <img> element ...
Web Performance
providing insight into web performance. in this article we define and compare these two performance monitoring approaches.populating the page: how browsers worka developer should strive to achieve these two goals. to understand how to improve performance and perceived performance, it helps to understand how the browser works.recommended web performance timings: how long is too long?there are no clear set rules as to what constitutes a slow pace when loading pages, but there are specific guidelines for indicating content will load (1 second), idling (50ms), animating (16.7s) and responding to user input (50 to 200ms).the business case for web performanceyou know web performance is important, but how do you convince clients and management to invest in performance and make it a priority. in this...
... slow pace when loading pages, but there are specific guidelines for indicating content will load (1 second), idling (50ms), animating (16.7s) and responding to user input (50 to 200ms).the business case for web performanceyou know web performance is important, but how do you convince clients and management to invest in performance and make it a priority. in this article, we'll discuss creating a clear business case to convince decision-makers to make the investment.understanding latencylatency is the time it takes for a packet of data to travel from 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 late...
Making PWAs work offline with Service workers - Progressive web apps (PWAs)
self.addeventlistener('install', (e) => { e.waituntil( caches.open('js13kpwa-v2').then((cache) => { return cache.addall(contenttocache); }) ); }); a new service worker is installed in the background, and the previous one (v1) works correctly up until there are no pages using it — the new service worker is then activated and takes over management of the page from the old one. ...
...kpwa-v2').then((cache) => { return cache.addall(contenttocache); }) ); }); a new service worker is installed in the background, and the previous one (v1) works correctly up until there are no pages using it — the new service worker is then activated and takes over management of the page from the old one. ...
Private Properties - Archive of obsolete content
however, the use of an underscore prefix is just a coding convention and is not enforced by the language: there is nothing to prevent a user from directly accessing a property that is supposed to be private. using closures another common technique, is to define private properties as variables and their getter and setter functions as a closure over these variables: function ...
preferences/service - Archive of obsolete content
of this branch. isset(name) parameters name : string preference name. returns boolean : returns whether or not the application preference name both exists and has been set to a non-default value by the user (or a program acting on the user's behalf). example: var name = "extensions.checkcompatibility.nightly"; if (require("sdk/preferences/service").isset(name)) { // ... } reset(name) clears a non-default, user-set value from the application preference name. if no user-set value is defined on name, the function does nothing. if no default value exists the preference will cease to exist. parameters name : string preference name. example: var name = "extensions.checkcompatibility.nightly"; require("sdk/preferences/service").reset(name); getlocalized(name, defaultvalue) gets the...
system/environment - Archive of obsolete content
access, set and clear environment variables. usage var { env } = require('sdk/system/environment'); you can get the value of an environment variable, by accessing the property with the name of the desired variable: var path = env.path; you can check for the existence of an environment variable by checking whether a property with that variable name exists: console.log('path' in env); // true console.log('foo' in env); // false you can set the value of an environment variable by setting the property: env.foo = 'foo'; env.path += ':/my/path/' you can unset an environment variable by deleting the property: delete env.foo; limitations there is no way to enumerate existing environment variables, also env won't have any enumerable properties: console.log(object.keys(env)); // [] envi...
Low-Level APIs - Archive of obsolete content
te with modules in the main process. remote/parent enables you to load modules, and privileged parts of your add-on in general, into child processes. stylesheet/style modify styles using stylesheet files or css rules. stylesheet/utils helper functions for working with stylesheets. system/child_process an implementation of the node.js child_process api. system/environment access, set and clear environment variables. system/events api for working with the application observer service. system/runtime access to information about firefox's runtime environment. system/unload register callbacks that are called when a module is unloaded. system/xul-app information about the application on which your add-on is running. tabs/utils functions for working with xul tabs and the xul tabbro...
Chrome Authority - Archive of obsolete content
r = require("x"+"hr"); var modname = "xpcom"; var xpcom = require(modname); var one = require("one"); var two = require("two"); the intention is that developers use require() statements for two purposes: to declare (to security reviewers) what sorts of powers the module wants to use, and to control how those powers are mapped into the module's local namespace. their statements must therefore be clear and easy to parse. a future manifest format may move the declaration portion out to a separate file, to allow for more fine-grained expression of authority. commands that build a manifest, like "jpm xpi" or "jpm run", will scan all included modules for use of cc/ci aliases (or the expanded components.classes forms). it will emit a warning if it sees the expanded forms, or if it sees a use of e.g...
Creating Reusable Modules - Archive of obsolete content
you then import and use these modules from other parts of your add-on using the require() statement, in exactly that same way that you import core sdk modules like page-mod or panel. it can often make sense to structure a larger or more complex add-on as a collection of modules. ...
HTML in XUL for rich tooltips - Archive of obsolete content
").setattribute("tooltiphtml", "<font color='green'>green foo</font>") }, onmousetooltip: function(event) { //get the html tooltip string assigned to the element that the mouse is over (which will soon launch the tooltip) var txt = event.target.getattribute("tooltiphtml"); // get the html div element that is inside the custom xul tooltip var div = document.getelementbyid("myhtmltipdiv"); //clear the html div element of any prior shown custom html while(div.firstchild) div.removechild(div.firstchild); //safely convert html string to a simple dom object, stripping it of javascript and more complex tags var injecthtml = components.classes["@mozilla.org/feed-unescapehtml;1"] .getservice(components.interfaces.nsiscriptableunescapehtml) .parsefragment(txt, false, null, div); //attach the do...
StringView - Archive of obsolete content
in the past, this had to be simulated by treating the raw data as a string and using the charcodeat() method to read the bytes from the data buffer. however, this is slow and error-prone, due to the need for multiple conversions (especially if the binary data is not actu...
Common Pitfalls - Archive of obsolete content
it's something the user typed in the url bar). the one exception 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...
Extension Etiquette - Archive of obsolete content
l labeled. don't hesitate to give long descriptions for each preference, as long as they are easy to understand, even for non-computer-savvy users. however, please make sure the default set of preferences is adequate — don't require people to tweak options in order to get your extension's core functionality. preferences' internal names internal firefox preference names for extensions or to be clear, the name of the preference as it appears in the about:config, should start with "extensions.," then the name of the extension, with a dot, then the name of the preference. for instance, a boolean for the reporter extension's option for hiding the privacy statement is "extensions.reporter.hideprivacystatement". general dependencies requiring a user to download another extension in order to use...
Chapter 2: Technologies used in developing extensions - Archive of obsolete content
and was originally published in japanese for the firefox developers conference summer 2007. shimoda-san is a co-author of firefox 3 hacks (o'reilly japan, 2008). before we dive into a thorough explanation, we'll quickly introduce the technologies used to develop firefox extensions. we will also look at the minimum knowledge you'll need to have in order to develop for firefox. technologies used to develop firefox extensions firefox and its extensions are both based on and developed with technologies widely used on the web. ...
Chapter 4: Using XPCOM—Implementing advanced processes - Archive of obsolete content
and was originally published in japanese for the firefox developers conference summer 2007. mr. shimoda is a co-author of firefox 3 hacks (o'reilly japan, 2008). this chapter explains how to use xpcom to implement advanced processes using only javascript. ...
Adding sidebars - Archive of obsolete content
ee using javascript and dom functions can become very convoluted, which is why trees are better used along with templates. this topic will be covered later when we look at different kinds of datasources and templates. adding style to a tree can also be challenging, which is why there's a guide specifically covering how to style a tree. looking at the bookmarks and history sidebars should make it clear that trees are quite customizable with css. « previousnext » this tutorial was kindly donated to mozilla by appcoast. ...
Adding windows and dialogs - Archive of obsolete content
wing sections: input controls numeric controls list controls there are some other aspects to take into account when handling input controls, which we cover in the following sections. groupboxes the groupbox element should be easy to understand: it groups a series of xul controls together. it's a box container with styling that is usually a visible border around its contents, so that it's clear what is being grouped together. it is frequently used with the caption element to 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 ...
The Box Model - Archive of obsolete content
f the "parrot" button was something much longer, the size ratio would not be kept. you can have even more control over the size of flexible elements using the minwidth, maxwidth, minheight and maxheight attributes, or their css counterparts: min-width, max-width, min-height and max-height. the latter are recommended to keep style code in the skin section of the chrome. as their names should make clear, you can control the flexibility boundaries of elements, thus preventing them from growing or shrinking too much. all css properties involving lengths should be handled with caution. we recommended that you use proportional units (em, %) instead of absolute units (px) whenever possible. using the former allows the ui to scale proportionately depending on font size settings, which are often cha...
Tabbed browser - Archive of obsolete content
, "@mozilla.org/browser/sessionstore;1", "nsisessionstore"); // create new tab, but don't load the content. var url = "https://developer.mozilla.org"; var tab = gbrowser.addtab(null, {relatedtocurrent: true}); gsessionstore.settabstate(tab, json.stringify({ entries: [ { title: url } ], usertypedvalue: url, usertypedclear: 2, lastaccessed: tab.lastaccessed, index: 1, hidden: false, attributes: {}, image: null })); reusing tabs rather than open a new browser or new tab each and every time one is needed, it is good practice to try to re-use an existing tab which already displays the desired url--if one is already open. following this practice minimizes the proliferation of tabs and browsers created by y...
Search Extension Tutorial (Draft) - Archive of obsolete content
/ if this is a localized preference, transform the value into an // appropriate data: url. if (localized) value = "data:text/plain," + encodeuricomponent(name + "=" + value.replace(/ /g, "\\u0020")); // save the original and new values. savedprefs[name] = [defaultprefs.getcharpref(name), value]; // change the default defaultprefs.setcharpref(name, value); // clear the user value if this is the first run, or the // new default is the same as the user value. if (firstrun || userprefs.getcharpref(name) == value) userprefs.clearuserpref(name); } function startup(data, reason) { firstrun = reason == addon_install; // change the default engine name. // an engine with this name must already exist. setpref("browser.search.defaulte...
Add-ons - Archive of obsolete content
of firefox itself. security best practices in extensions this document is intended as a guide for developers to promote best practices in securing your extension. your goal is to keep your users safe. some items mentioned are strict guidelines, meaning that if you don't follow them then your add-on will not be approved on mozilla add-ons. other items are recommendations. the difference will be clearly flagged. setting up an extension development environment this article provides suggestions for how to set up your mozilla application for extension development. these details apply to firefox, thunderbird, and seamonkey (version 2.0 and above). tabbed browser here you should find a set of useful code snippets to help you work with firefox's tabbed browser. the comments normally mark where y...
An Interview With Douglas Bowman of Wired News - Archive of obsolete content
one of the web's oldest news sites, wired news draws between 20 and 25 million page views every month. on october 11, 2002, wired launched a brand-new site design that uses validating xhtml for its structure and a small collection of css files for its layout. the new design clearly shows what some experts have been saying: that standards-based design can be visually compelling and preserve the interface conventions we've come to expect from web pages. the brains and primary driving force behind this compelling new design is douglas bowman, network design manager for terra lycos, who graciously agreed to an interview and in the process shed a lot of light on what goes into a standards-based redesign. wired news redesign in a nutshell driven by xhtml 1.0 transitional and css; allows...
Creating reusable content with CSS and XBL - Archive of obsolete content
ibute(this, "anonid", "square") ]]></field> <field name="button"><![cdata[ document.getanonymouselementbyattribute(this, "anonid", "button") ]]></field> <method name="dodemo"> <body><![cdata[ this.square.style.backgroundcolor = "#cf4" this.square.style.marginleft = "20em" this.button.setattribute("disabled", "true") settimeout(this.cleardemo, 2000, this) ]]></body> </method> <method name="cleardemo"> <parameter name="me"/> <body><![cdata[ me.square.style.backgroundcolor = "transparent" me.square.style.marginleft = "0" me.button.removeattribute("disabled") ]]></body> </method> </implementation> <handlers> <handler event="click" button="0"><![cdata[ ...
Defining Cross-Browser Tooltips - Archive of obsolete content
ay annotate any number of elements. please consult an element's definition to verify that it supports this attribute... values of the title attribute may be rendered by user agents in a variety of ways. for instance, visual browsers frequently display the title as a "tool tip" (a short message that appears when the pointing device pauses over an object). between these two passages, it is fairly clear that the proper method for defining a "tooltip" for an image (or, indeed, for any element) is to use the title attribute. the solution the most obvious solution is to use the alt and title attributes for their intended purposes, instead of adhering to their historical misuses. a quick check of various user agents showed that title attribute contents were displayed as a "tooltip" in: gecko-ba...
Images, Tables, and Mysterious Gaps - Archive of obsolete content
isking other layout upset with the following rule: td {line-box-contain: font replaced;} /* proposed for css3 */ there are other possible fixes contained within the current css3 working drafts, such as line-height-policy. obviously, the sooner a solution can be found and implemented, the happier authors everywhere will be. recommendations absent support for css3, it is difficult to provide a clear set of steps for fixing every instance of these problems, because the best solution for a given document will greatly depend on its structure. if your document uses transitional markup, make sure your doctype reflects that fact and does not trigger "standards" mode. this will prevent browsers from using standards-based rendering, and thus all the image-layout problems are avoided. if you're using...
Monitoring WiFi access points - Archive of obsolete content
"d"><p></p></div> <div id="c"><p></p></div> </body> </html> the nsiwifilistener object the first thing the code above does is to prototype the listener object that will be receiving notifications of changes to the access point list. this object is described in lines 11 through 40 in the code above. the onchange() method (lines 13 through 27) begins by enabling universalxpconnect privileges, then clearing out the div (d) that will receive the updated list of access points. then the loop in lines 19-22 iterates over the list of access points received in the accesspoints array and adds them to the html in the div. then the c div is updated with the number of times the list has been refreshed. the onerror() method simply opens an alert that displays the error code received. starting to monitor acc...
Visualizing an audio spectrum - Archive of obsolete content
* unused, but it's there */ signal = new float32array(fb.length / channels), magnitude; for (var i = 0, fbl = framebufferlength / 2; i < fbl; i++ ) { // assuming interlaced stereo channels, // need to split and merge into a stero-mix mono signal signal[i] = (fb[2*i] + fb[2*i+1]) / 2; } fft.forward(signal); // clear the canvas before drawing spectrum ctx.clearrect(0,0, canvas.width, canvas.height); for (var i = 0; i < fft.spectrum.length; i++ ) { // multiply spectrum by a zoom value magnitude = fft.spectrum[i] * 4000; // draw rectangle bars for each frequency bin ctx.fillrect(i * 4, canvas.height, 3, -magnitude); } } var audio = d...
Locked config settings - Archive of obsolete content
note: in recent versions of mozilla (tested on windows and linux, with 1.5, 1.6 and 1.7b), the mozilla.cfg file needs to be placed in mozilla's root directory, rather than default\pref where all.js resides. ...
Developing New Mozilla Features - Archive of obsolete content
facilitate this. it’s possible developers may not pay much attention to you because they believe your proposed feature is not a high priority, or is not wanted at all, or that you haven’t demonstrated that you understand the codebase and mozilla coding practices well enough for them to spend a lot of time with you. in some cases the developers may be in error and staff will work to make this clear and get you connected. in other cases, mozilla.org staff may agree with the developers that it does not make sense for them to spend much time assisting with your project. this is a painful setting and we hope it doesn’t happen often. but our developers are a precious commodity and their time is probably the most important resource we have. it’s also possible that a developer is over-worked ...
Editor Embedding Guide - Archive of obsolete content
lines contained in the current selection. getcommandstate "state_attribute" (cstring) docommand "state_attribute" (cstring) "left", "right", "center", "justify" cmd_inserthtml cmd_insertlinknoui cmd_insertimagenoui cmd_inserthr cmd_charset sets the charset for the document. getcommandstate "state_attribute" (cstring) docommand "state_attribute" (cstring) note there must be a clear undo stack or this will not work. cmd_copy copies current selection. getcommandstate "state_enabled" (boolean) docommand no parameter note getcommandstate in these cases will return whether or not it is possible to call docommand. this will not really give you any concrete information on the state of the command. cmd_cut cuts current selection. getcommandstate "state_enabled" (b...
Layout FAQ - Archive of obsolete content
ffb1c {330,225,0,0} [state=00000020] [content=035aebf0] > > the linebox is used to contain everything on a single line: example how do you fix inconsistent float behavior in firefox involving a two column layout using display:table and floating div elements? this is a bug in firefox. you can work around it by removing display:table in the style rule with the "#main" selector or adding clear:both to it. why does move movement disappear when i use mouse events to click and drag? since the dragging action is involved, you might need to disable it. try using event.preventdefault() what is the purpose of the ns_lossyconvertucs2toascii() function? this function converts an nsastring to an nsacstring by assuming that all the 16-bit units are ascii and just dropping the high byte on...
JavaScript crypto - Archive of obsolete content
e name as one of the modules that // has already been installed miscellaneous domstring random(in long numbytes); unimplementedyou can use window.crypto.getrandomvalues instead. void logout(); logs the user out of all the cryptographic tokens. the next private operation on any token will require the user password again. the ssl session cache is also cleared (from firefox 1.5 upward). this means the master password will be requested the next time a saved password will be accessed after this function is called. this also means the ssl client authentication state will be erased for ssl sites with client authentication, and a client certificate prompt will appear again the next time the user connects to the site. note: this function provides a conv...
Migrate apps from Internet Explorer to Mozilla - Archive of obsolete content
iant value) sets a parameter in the imported xslt stylesheet. variant getparameter(string namespaceuri, string localname) gets the value of a parameter in the imported xslt stylesheet. void removeparameter(string namespaceuri, string localname) removes all set parameters from the imported xslt stylesheet and makes them default to the xslt-defined defaults. void clearparameters() removes all set parameters and sets them to defaults specified in the xslt stylesheet. void reset() removes all parameters and stylesheets. original document information author(s): doron rosenberg, ibm corporation published: 26 jul 2005 link: http://www.ibm.com/developerworks/we...y/wa-ie2mozgd/ ...
Table Cellmap - Archive of obsolete content
row- or colspan attribute is different from 1. a colspan lets add a cell to the second row in the 2x2 table and let the second cell in the first row span over two cells. <table> <tr><td>cell 1</td><td colspan="2">cell 2</td></tr> <tr><td>cell 3</td><td>cell 4</td><td>cell 5</td></tr> </table> table cell map would be: row 0 : c0,0 c0,1 c row 1 : c1,0 c1,1 c1,2 while it is clear that in the cells that are the origin of a table cells one will find a address the more interesting question is, what will be the content in the upper right cell. the bitfield will hold a 0x00090001. #define span 0x00000001 // there a row or col span #define row_span 0x00000002 // there is a row span #define row_span_0 0x00000004 // the row span is 0 #define row_span_of...
Table Layout Regression Tests - Archive of obsolete content
warning: the content of this article may be out of date. while the information on the layout debugger is still useful, the testing information is much less relevant now than 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...
Tamarin Build System Documentation - Archive of obsolete content
all of the buildsteps for a build and the time each buildstep took scroll down to see previous builds triggered at the bottom of the page click on the [next page] link to display more previous builds what are the goals of the build system (qos)? to provide quick and accurate results of building and testing tamarin on supported platforms and configurations to represent the build results in a clear and concise manor please give use feedback if you have any comments or suggestions to improve the build system how to add tests to the smokes? the list of smoke tests are located in the tamarin-repository, test/run-smokes.txt, assume the start directory is test format is cd testdir; command to run test above the test should be a # comment describing why the test in the smokes, when test failed...
Venkman Introduction - Archive of obsolete content
tically displayed in the source code view. the line in question will be highlighted in yellow to make it easy to spot. clicking in the left margin of this view will set a breakpoint at that line. if the breakpoint is successfully set, the margin will show the letter "b" on a red background, and both the loaded scripts view and interactive session view will provide feedback. the breakpoint can be cleared by clicking in the margin again (on the letter "b"). breakpoints cannot be set on lines which do not contain executable code, such as blank and comment lines. for these lines, the interactive session view will display an error message explaining why the breakpoint could not be set. breakpoints can also be set and cleared from the interactive session view, with the break and fbreak commands. th...
Using Breakpoints in Venkman - Archive of obsolete content
using breakpoints and the interactive view, you can change the values of the variables that venkman displays (only in the context of the debugging environment itself) and see how these changes affect the execution of the code. for more information about the sorts of actions you can take in venkman when you're at a breakpoint, see the debugging basics section of the introductory venkman article. clearing breakpoints to clear the breakpoint, click on the margin twice. the first click will clear the hard breakpoint and leave you with only a future breakpoint, which is represented by a yellow letter "f". a second click will remove the future breakpoint as well. advanced breakpoints venkman allows you to associate a breakpoint with a script that will be executed in the scope of the function when ...
Venkman - Archive of obsolete content
#venkman on irc.mozilla.org report a bug in venkman if you find a problem with venkman, please follow directives mentioned at venkman faq section 5.4 and then you may report a bug on javascript debugger component. related topics javascript, web development, developing mozilla original document information author(s): robert ginda other contributors: doctor unclear last updated date: july 13, 2007 copyright information: portions of this content are © 1998–2007 by individual mozilla.org contributors; content available under a creative commons license | details. ...
registerChrome - Archive of obsolete content
d-chrome.txt file in the chrome directory to see how and where the registerchrome function has registered your package with the chrome registry. example example assumes your xpi file is in plugins folder and rdf file is in resources subfolder of xpi. you should probably avoid this call (in the case you are copy/pasting from older install scripts) for plugin installation in firefox 2.x. it is unclear what, if anything, does this "chrome registration" accomplish. registerchrome( package | delayed_chrome, getfolder("plugins"), "resources"); ...
norestorefocus - Archive of obsolete content
...
disableautoselect - Archive of obsolete content
if this attribute is false, the selection is never updated to match the text box. this attribute applies only to editable menulists. ...
icon - Archive of obsolete content
Archive › Mozilla › XUL › Attribute › icon
« xul reference home icon mozilla 1.8 type: string this attribute should be used to set the usage for common buttons. some platforms display these buttons with a small icon indicating their usage. this should be used in place of the image attribute. possible values include: accept, cancel, help, open, save, find, clear, yes, no, apply, close, print, add, remove, refresh, go-forward, go-back, properties, select-font, select-color, network. if you are using a button that matches one of these common usages, use the icon attribute to indicate this. see the appearance of the different icons on some available platforms. ...
Building accessible custom components in XUL - Archive of obsolete content
ll need to declare the namespace (xmlns:x2="http://www.w3.org/tr/xhtml2") so we can add an xhtml2:role attribute to each xul element. the role attribute value is also in a namespace. we will need to declare this namespace as well (xmlns:wairole="http://www.w3.org/2005/01/wai-rdf/guiroletaxonomy#"), and then use this namespace prefix (wairole:) as part of the role attribute value. this will become clearer with some concrete examples: the grid element is the container for the entire control; it gets a role of "wairole:spreadsheet". some of the description elements are row headers, and others are column headers. they each get the appropriate role, "wairole:rowheader" or "wairole:columnheader". each label element is an individual cell and needs a role of "wairole:gridcell". this means we actually...
Index - Archive of obsolete content
Archive › Mozilla › XUL › Index
455 blur xul methods, xul reference no summary! 456 cancel xul methods, xul reference no summary! 457 canceldialog xul methods, xul reference no summary! 458 centerwindowonscreen xul methods, xul reference no summary! 459 checkadjacentelement xul methods, xul reference no summary! 460 clearresults needscontent, needshelp, xul methods, xul reference no summary! 461 clearselection xul methods, xul reference no summary! 462 click xul methods, xul reference no summary! 463 close xul methods, xul reference no summary! 464 collapsetoolbar xul methods, xul reference no summary! 465 cont...
moveByOffset - Archive of obsolete content
items that are hidden are skipped. ...
reset - Archive of obsolete content
Archive › Mozilla › XUL › Method › reset
...
Methods - Archive of obsolete content
« xul reference home acceptdialog additemtoselection addpane addprogresslistener addsession addtab addtabsprogresslistener advance advanceselectedtab appendcustomtoolbar appendgroup appenditem appendnotification blur cancel canceldialog centerwindowonscreen checkadjacentelement clearresults clearselection click close collapsetoolbar contains decrease decreasepage docommand ensureelementisvisible ensureindexisvisible ensureselectedelementisvisible expandtoolbar extra1 extra2 focus getbrowseratindex getbrowserfordocument getbrowserfortab getbrowserindexfordocument getbutton getdefaultsession geteditor getelementsbyattribute getelementsbyattributens getformattedstring gethtmleditor getindexoffirst...
MenuButtons - Archive of obsolete content
doesn't indicate which view is selected. if you do want this indication, you should use a menulist instead. the same technique can be used for toolbarbuttons as well as buttons. in the example below a toolbarbutton with an image has a menu associated with it. <toolbarbutton type="menu" image="cookies.png"> <menupopup> <menuitem label="block cookies" type="checkbox"/> <menuitem label="clear cookies"/> </menupopup> </toolbarbutton> the 'menu-button' button the 'menu-button' type of button is used when you want to attach a menu to a button but want to have a default action carried out when the button is pressed by itself. this is accomplished by dividing the button into two parts, one with the label and image to carry out the default command and the second to show the menu. to cr...
MenuItems - Archive of obsolete content
he checked attribute will not be updated automatically. note that the code has been reversed in the condition blocks to hide the toolbar when the menuitem is checked and show the toolbar when the menuitem is not checked because the checked state hasn't been modified. the example assumes that the showtoolbar() function might fail so if it returns false, the checked attribute is not modified. when clearing the checked state, the checked attribute should be removed rather than just set to false. in the example, this is done by using the removeattribute method. radio menu items a radio menu item os used when you wish to have a group of menuitems in which only one can be checked at a time. this works similarly to the checkbox type, except when selecting an item, all others in the same group are a...
MenuModification - Archive of obsolete content
ed to add new nodes within another node. the appenditem method is specific to menus, as well as some other specific elements, and is simpler to use to append new menuitem elements to a menu. if we were to use the example above, we would also want to make sure to remove the items again in a popuphiding event listener. otherwise, a new submenu would be added every time the menu is opened, which is clearly not desirable. another possibility is to ensure that the menu is only added once. the following shows how the addsubmenu function above might be rewritten to handle this case. <script> function addsubmenu() { var popup = document.getelementbyid("file-popup"); if (popup.haschildnodes()) return; var newmenu = document.createelement("menu"); popup.appendchild(newmenu); newmenu.labe...
PopupEvents - Archive of obsolete content
is fired regardless of how the popup was hidden, whether because the user selected an item from a menu, or if the user clicked outside the popup, or if the user pressed escape to cancel the menu. the popupshowing and popuphiding event will also be fired as the user rolls the mouse around on a menu bar, showing and hiding different menus and submenus. in this example, the contents of a textbox are cleared whenever a popup is hidden. <panel onpopuphiding="document.getelementbyid('search').value = '';"> <textbox id="search"/> <button label="search" oncommand="dosearch();"/> </panel> you can prevent a popup from hiding by calling the event's preventdefault method. this way, the popup will not be closed. usually, you should not do this. if you wanted to ensure that a value was entered for insta...
Filtering - Archive of obsolete content
ies/country-ont#country"> remember that the only requirement is that the starting point be a resource, but it doesn't matter what resource is used. the query statements will need to iterate over the arcs pointing into the type resource. since we want the arcs pointing into the type, we need to determine the source or subject of a triple. look at the resulting rdf triples above again if this is unclear. the starting node is 'http://www.daml.org/2001/09/countries/country-ont#country'. we need to iterate over the 'type' predicate to find the individual countries. a second triple is used to get the title for the country. <query> <content uri="?start"/> <triple subject="?country" predicate="http://www.w3.org/1999/02/22-rdf-syntax-ns#type" object="?start"/> <triple subject...
RDF Modifications - Archive of obsolete content
hanges that affect a binding often, a new rdf triple is created in the datasource which would only affect a template rule's bindings. since the bindings section of a rule specifies predicates that may optionally have values, the addition or removal or this rdf data would never be able to add or remove a new result. at the very most, the change would cause a label to be filled in with a value, or cleared when removing an rdf triple. as described earlier, the query part of a template is checked first to see if it would cause a change. after this, the bindings are examined. this is done whether the query produced a new result, removed one, or the content was not affected, since a binding could have affected any existing results. it's possible, for instance, for every existing row to be affected b...
RDF Query Syntax - Archive of obsolete content
the ?start variable is repeated for each result. this is because the builder copies the existing data for each new potential result and adds the new data. internally, this isn't quite true; the builder actually maintains only one copy of the similar data but uses data structures in such a way which make it appear as if it were duplicated. you may find this a bit confusing, but this should become clearer later with more specific and practical examples. since the triple was the last statement, the builder moves on to the content generation phase, creating matches out of the three potential results. « previousnext » ...
Special Condition Tests - Archive of obsolete content
uld be created that would only match a <vbox> element. this is useful for recursive templates, since the inner iterations may use different content. it's most useful to distinguish between the outer and inner levels during template generation. for the bookmarks toolbar, the outer content is inserted into an <hbox>, but at lower levels, the content will be inserted into a <menu> in case you aren't clear, the tag that must match for the outer iteration is the root element, the one with the datasources attribute on it. for inner iterations, it will be the element with the uri attribute from the previous iteration. here is a previous example, rewritten to use the parent matching syntax: <vbox datasources="people.xml" ref="*" querytype="xml"> <template> <query expr="*"/> <rule parent="vbox...
Template Logging - Archive of obsolete content
y inside the <template> element with no other kinds of elements as siblings. no member variable found. action body should have an element with uri attribute the member variable could not be determined. you should specify an element inside the first <action> body with a uri attribute. you can also specify the member attribute on the template. either way, the member variable isn't known so it isn't clear what value to use for each generated result id. <where> element is missing a subject attribute every <where> should have a subject attribute that specifies what you are comparing. <where> element is missing a rel attribute every <where> should have a rel attribute that specifies what relation condition you are checking. <where> element is missing a value attribute every <where> should have a valu...
XML Assignments - Archive of obsolete content
xpressions for the assign element are evaluated using each result node as the context. for each result, the ?namelength variable will be assigned the length of the name attribute on the result node, and the ?siblings variable will be assigned the number of sibling nodes the result has. (in this case, the number of xml node siblings in the document, not the number of real siblings the people have, clearly the people in the datasource aren't actually siblings). naturally, the number of siblings will be the same for all children, but you could imagine a more complex query expression that generated nodes where this wasn't actually the case. the two variable assignments may then be used in the action body to replace attributes in the generated content. if a variable is used in the action that doesn'...
XML Templates - Archive of obsolete content
istbox> here, an anchor reference, starting with a number sign (#) is used for the datasources attribute. it refers to an element with that id (without the number sign) and uses that node as the source xml node instead of a separate file. otherwise the data included inline and the template are the same. note the only change is that the addition of the xmlns attribute on the data; this is used to clear the namespace used for the elements in the data, otherwise they become xul elements. you can also specify a namespace. if so, you will need to ensure that prefixes are defined within the template as well, so that they can be used in the xpath expressions. the namespace prefixes that may be used in an xpath expression are those that are defined on the query or assign element where the expression i...
The Joy of XUL - Archive of obsolete content
upporting all mozilla platforms. separation of presentation from application logic one of the major downfalls of most web applications is the tight coupling of user interface elements with client application logic. this poses a significant problem in team environments because the skills required to develop these two parts are often satisfied by different people. xul provides a clear separation among the client application definition and programmatic logic ("content" consisting of xul, xbl, and javascript), presentation ("skin" consisting of css and images), and language-specific text labels ("locale" consisting of dtds and string bundles in .properties files). the layout and appearance of xul applications can be altered independently of the application definition and logic. ...
Custom toolbar button - Archive of obsolete content
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, remove the sections for applications where your button does not work. for example, if your button only works in thunderbird, remove the sections for firefox and sunbird. do the same in button.xul and ...
Adding Event Handlers to XBL-defined Elements - Archive of obsolete content
the first (and only) element within the content element. the value property is retrieved which will provide the text within the textbox. this is then assigned to the clipboard field. the result is copying the text in the textbox into this special clipboard. document.getanonymousnodes(this)[0].value='' the text of the textbox is then assigned a value of a null string. this effectively clears the text in the textbox. a copy operation is similar but does not clear the text afterwards. pasting is the opposite where the value of the textbox is assigned from the value in the clipboard field. if we were creating a real implementation of these clipboard keyboard shortcuts, we would probably use the real clipboard interface and handle the current selection as well. in the next section, we'...
Adding HTML Elements - Archive of obsolete content
ekeeper/there.is.only.xul"> then, you can use html tags as you would normally, keeping in mind the following: you must add a html: prefix to the beginning of each tag, assuming you declared the html namespace as above. the tags must be entered in lowercase. "quotes" must be placed around all attribute values. xml requires a trailing slash at the end of tags that have no content. this may be clearer from the examples below. using html elements you can use any html tag although some such as head and body are not really useful. some examples of using html elements are shown below. <html:img src="banner.jpg"/> <html:input type="checkbox" value="true"/> <html:table> <html:tr> <html:td> a simple table </html:td> </html:tr> </html:table> these examples will create an image ...
Creating a Skin - Archive of obsolete content
s that have their selected attribute set to true. it makes the text in the selected tab appear bold, underlined and dark blue. note in the image that this style has applied only to the first tab, because it's the selected one. adding toolbar icons it is somewhat difficult to distinguish the buttons on the toolbar from the commands on the menu. we could add some icons to the buttons to make them clearer. mozilla composer provides some icons for open and save buttons, which we'll just use here to save time. we can set the image for a button using the list-style-image css property. #opensearch { list-style-image: url("chrome://editor/skin/icons/btn1.gif"); -moz-image-region: rect(48px 16px 64px 0); -moz-box-orient: vertical; } #savesearch { list-style-image: url("chrome://editor/skin/i...
Document Object Model - Archive of obsolete content
the other window (for example, the test.xul window). to do this, we can do the following: alert(window.opener.gettext()); each window has an opener property which holds the window object that opened this one. in this example, we retrieve the opener window and call the gettext() function declared in a script used there. note that we qualified the property with the 'window' identifier just to be clearer. the window's open() method also returns a reference to the new window so 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 lev...
Keyboard Shortcuts - Archive of obsolete content
uch as the enter key or the function keys). the key attribute can only be used for printable characters. another attribute, keycode can be used for non-printable characters. the keycode attribute should be set to a special code which represents the key you want. a table of the keys is listed below. not all of the keys are available on all keyboards. ...
Manipulating Lists - Archive of obsolete content
e this function requires an index we can convert between an item and an index using the getindexofitem() function. there is also a corresponding getitematindex() function to do the reverse. the nsidomxulmultiselectcontrolelement interface also provides methods for modifying the selected items. for instance, the additemtoselection() function adds a new item to the set of selected items, without clearing the existing selection. the removeitemfromselection() function removes a single item from the selection. list scrolling if there are more rows in the listbox than can be displayed, a scroll bar will appear to allow the user to scroll the list. the scroll position may be adjusted using a couple of listbox methods. the scrolltoindex() method scrolls to a given row. this listbox will scroll su...
Modifying a XUL Interface - Archive of obsolete content
in the next section. manipulating basic elements the main xul elements such as buttons, checkboxes and radio buttons may be manipulated using a number of script properties. the properties available are listed in the element reference as those available are different for each element. common properties that you will manipulate include the label, value, checked and disabled properties. they set or clear the corresponding attribute as necessary. label and value properties examples here is a simple example which changes the label on a button: example 3 : source view <button label="hello" oncommand="this.label = 'goodbye';"/> when the button is pressed, the label is changed. this technique will work for a variety of different elements that have labels. for a textbox, you can do something similar f...
XUL Structure - Archive of obsolete content
-- bookmarks files go here -- preferences -- preferences files go here -- . . . this is easily recognizable as a content package, as the top-level directory is called content. for skins, this directory will usually be called skin and for locales, it will usually be called locale. this naming scheme isn't necessary, but this is a common convention to make the parts of a package clearer. some packages may include a content section, a skin, and a locale. in this case, you will find a subdirectory for each type. for example, chatzilla is distributed in this way. the content/browser directory contains a number of files with .xul and .js extensions. the xul files are the ones with the .xul extension. the files with .js extensions are javascript files containing scripts that handl...
XUL Changes for Firefox 1.5 - Archive of obsolete content
alog> binding (using their names); or to none - in which case no button is set to be the default. button: icon property the icon property on a button may be used to set stock icons on a button, used on some platforms. for instance <button icon="help"> will create a button with a help icon. this is used typically on gnome systems where possible values are: accept, cancel, help, open, save, find, clear, yes, no, apply, close, print, add, remove, refresh, go-forward, go-back, properties, select-font, select-color, network. <menulist> items in a <menulist> support the description attribute to allow for extra descriptive text to appear beside an item's label. the menulist modification methods appenditem and insertitemat take an extra description argument when creating items this way. <listbox> ...
button - Archive of obsolete content
checked at a time. if the user selects one the buttons, the others in the group are unchecked. icon mozilla 1.8 type: string this attribute should be used to set the usage for common buttons. some platforms display these buttons with a small icon indicating their usage. this should be used in place of the image attribute. possible values include: accept, cancel, help, open, save, find, clear, yes, no, apply, close, print, add, remove, refresh, go-forward, go-back, properties, select-font, select-color, network. if you are using a button that matches one of these common usages, use the icon attribute to indicate this. see the appearance of the different icons on some available platforms. image type: uri the uri of the image to appear on the element. if this attribute is emp...
menulist - Archive of obsolete content
in a menu you can add the following css rule when you want to use the value none: menupopup > menuitem, menupopup > menu { max-width: none; } disableautoselect type: boolean if this attribute is true or omitted, the selected item on the menu will update to match what the user entered in the textbox. if the text does not match any of the items in the list, the menu selection is cleared. if this attribute is false, the selection is never updated to match the text box. this attribute applies only to editable menulists. disabled type: boolean indicates whether the element is disabled or not. if this attribute is set, the element is disabled. disabled elements are usually drawn with grayed-out text. if the element is disabled, it does not respond to user actions, it canno...
panel - Archive of obsolete content
Archive › Mozilla › XUL › panel
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="console.log('the onpopuphidden method of id=top was called.');"> <menuitem label="item 1...
preference - Archive of obsolete content
displayed in the ui is obtained from the defaultvalue property. valuefrompreferences gets and sets the value stored in the user preference, specified in name. (this always accesses the nsiprefbranch apis regardless of the instantapply mode in effect). methods reset() return type: no return value resets the preference to its default value. for a textbox it also clears the undo transaction list (gecko 1.9). type getelementvalue(in domelement element); retrieves the value that should be written to preferences based on the current state of the supplied element. this function calls onsynctopreference. boolean iselementeditable(in domelement element) returns true, if the given element is "editable" (see below). void setelementvalue(in domelement element); ...
preferences - Archive of obsolete content
« xul reference home [ examples | attributes | properties | methods | related ] overview <preferences> is a container for <preference> elements. it's supposed to be a child of <prefpane> element. <preferences> element should contain one or more <preference> elements. note: it's not clear which of the following methods and properties are public. examples <preferences> <preference id="pref_one" name="extensions.myextension.one" type="bool"/> <preference id="pref_two" name="extensions.myextension.two" type="string"/> ... etc ... </preferences> attributes these ought to be readonly; three of these could be merged into a single member attribute nsiprefservice service; the preferences service. attribute nsiprefbranch rootbranch; the root prefs branch. attr...
textbox - Archive of obsolete content
e. methods decrease() return type: no return value decreases the value of the scale or number box by the increment. increase() return type: no return value increases the value of the scale or number box by the increment. reset() return type: no return value resets the preference to its default value. for a textbox it also clears the undo transaction list (gecko 1.9). select() return type: no return value selects all the text in the textbox. setselectionrange( start, end ) return type: no return value sets the selected portion of the textbox, where the start argument is the index of the first character to select and the end argument is the index of the character after the selec...
Getting started with XULRunner - Archive of obsolete content
mpatible with; make sure that you set them so that the version of xulrunner you're using is in that range, or your application won't work. note: make sure your application name is lowercase and longer than 3 characters step 5: set up the chrome manifest the chrome manifest file is used by xulrunner to define specific uris which in turn are used to locate application resources. this will become clearer when we see how the “chrome://” uri is used. application chrome can be in a single or a few jar files or uncompressed as folders and files. i am using the uncompressed method for now. here is the chrome/chrome.manifest: content myapp content/ as mentioned in step 3, the default location of the chrome.manifest has changed in xulrunner 2.0, so we also need a simple chrome.manifest in the ...
application/http-index-format specification - Archive of obsolete content
encountered that a parser does not understand the parser is required to ignore that line. there is no line length limit. all lines must be terminated by a carriage return followed by a line feed. number codes 100 a human readable comment line. machine parsers should ignore this data. this data is not intended for display to the end user and is only meant as a comment to make the file format clear to a human interpreter. 101 pre formatted human readable information line. this data is intended for the end user of the file format data if there is one. this data should be presented to the user when they are viewing data drawn from the file. 102 a human readable information line in html format. this data is intended for the end user of the file format data if there is one. this data shou...
reftest opportunities files - Archive of obsolete content
many of these were checked with the layout regression test tool, which has been described as difficult to use and it apparently reported a lot of regressions that were not errors. if you can look at the html in one of these pages, and can see a way to get the same visual ouptut, then that is an obvious reftest opportunity. for example, if some html is in an unexpected place and is supposed to be ignored, then we can match against an html file that is missing that extra mark-up. ...
2006-10-20 - Archive of obsolete content
- october 14-20, 2006 announcements eudora goes open source both qualcomm and mozilla will participate in enhancing the capabilities and ease of use of both eudora and thunderbird. discussions how to use the tb/ab lastmodifieddate item and how to solve the problem regarding to this item. there is a link provided might solve the stated problem. however, detail info of the problem is not clear, no futher suggestion or solution is provided thus far. stefan göppert suspect thunderbird inserts a wrong char("") in the bcc-field and want to confirm this issue. no respond posted for this discussion yet. meetings none for this week. ...
Why RSS Content Module is Popular - Including HTML Contents - Archive of obsolete content
. it is only suppose to be used to includeplain text. but rss still leaves us without a way to include html contents. the rss content module fills this gap. note: do not put anything butplain text into the rss <description> element. although it has become common practice to use the rss <description> element and put non-plain text data in it. it is not actually allowed. the rss 2.0 specification clearly states that “entity-encoded html is allowed“ and even provides examples showing exactly the syntax above (using cdata and unencoded html). the wording of this note should be reconsidered. an example using the most popular element of the rss content module is shown below: <?xml version="1.0"?> <rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/" > ...
Introduction to Public-Key Cryptography - Archive of obsolete content
ted resource. these are the steps shown in figure 4: in response to an authentication request from the server, the client displays a dialog box requesting the user's name and password for that server. the user must supply a name and password separately for each new server the user wishes to use during a work session. the client sends the name and password across the network, either in the clear or over an encrypted ssl connection. the server looks up the name and password in its local password database and, if they match, accepts them as evidence authenticating the user's identity. the server determines whether the identified user is permitted to access the requested resource, and if so allows the client to access it. with this arrangement, the user must supply a new password for ea...
Developing cross-browser and cross-platform pages - Archive of obsolete content
the top-level if clause looks to see if there is support for a method called getelementbyid on the document object, which is the one of the most basic levels of support for the dom in a browser. if there is, the code sees if document.getelementbyid(id_attribute_value) returns a reference to an existing element, which it then checks for a style object. if the...
Using the W3C DOM - Archive of obsolete content
anel.firstchild) { spanel.removechild(spanel.firstchild); } spanel.appendchild(document.createtextnode('some gall')); } </script> </body> the first part of the code gets a reference to the element. it then tests for support for textcontent, then innertext and uses which ever is supported. if neither is supported, it assumes support for basic dom 1 methods and uses those. it should be clear that translating scripts to modify document content is not a trivial undertaking. the benefit of such a conversion is that the script will work in w3c dom-compliant browsers. useful references on changing an element's text using the dom whitespace in the dom by david baron element.innerhtml speed and performance comparison between innerhtml attribute and dom's nodevalue when modifying the t...
::-ms-expand - Archive of obsolete content
...
E4X for templating - Archive of obsolete content
...
ECMAScript 2015 support in Mozilla - Archive of obsolete content
es] (firefox 41) set (firefox 13) set iteration with for...of (firefox 17) set.prototype.foreach() (firefox 25) set.prototype.entries(), set.prototype.keys(), set.prototype.values() (firefox 24) constructor argument: new set(null) (firefox 37) monkey-patched add() in constructor (firefox 37) get set[@@species] (firefox 41) weakmap (firefox 6) weakmap.clear() (firefox 20) optional iterable argument in weakmap constructor (firefox 36) constructor argument: new weakmap(null) (firefox 37) monkey-patched set() in constructor (firefox 37) weakset (firefox 34) constructor argument: new weakset(null) (firefox 37) monkey-patched add() in constructor (firefox 37) new math functions math.imul() (firefox 20) math.clz32() (fir...
Back to the Server: Server-Side JavaScript On The Rise - Archive of obsolete content
with the password of prhino. the sql statement is prepared, executed, and printed with the help of the metadata obtained from the resultset. sample output is shown in listing 2. id: 1 first_name: sammy last_name: hamm department: it title: network administrator ---------- id: 2 first_name: nigel last_name: bitters department: finance title: accounting manager ... it’s clear to see that with just a few lines of code, we can easily take advantage of sql data stores in javascript. the sample script in listing 1 could be factored out to it’s own function to retrieve the set of employee information, or abstracted further into a more generic data handler class. next we’ll take a look at another powerful feature in rhino, e4x processing. e4x (e...
Reference - Archive of obsolete content
dt) since the for each...in loop is a 1.6 feature (not a 1.5 feature), maybe someone should rename this page/category to be either a general javascript reference or update it to be the 1.6 reference. having 1.6 features defined in the 1.5 reference might be confusing. cstevens 10:23, 20 december 2006 (pst) we do plan to move the pages around, see core javascript 1.5 reference/reorg, but it's not clear when that will happen. in the meantime, newer features from js 1.6 (and hopefully someone will add js 1.7 features too) are being added to the reference with appropriate version information on the page itself. yes, it can be slightly confusing, but it's better than no documentation for newer features at all. --nickolay 01:53, 22 december 2006 (pst) yes, seeing stuff that doesn't apply to 1.5 on...
XForms Upload Element - Archive of obsolete content
ype restrictions the upload element can be bound to a node of type xsd:anyuri, xsd:base64binary or xsd:hexbinary or any type derived from one of these. representations the xforms upload element is represented by visually combining three widgets: a text field that shows the uri of the selected file, a button to open the file picker dialog which allows the user to select a file, and a button to clear the text field and the reference to the file from the bound node (xhtml only). characteristics analogous widget is <xhtml:input type="file"/> ...
Choosing Standards Compliance Over Proprietary Practices - Archive of obsolete content
ance that the standard they choose to incorporate into their development process will be relevant in the future. in other words, there must be long-term potential. a fundamental mistake that many organizations make is to use proprietary methods, software, code, or standards. following a proprietary path has led many organizations down disastrous paths. case in point: xerox corporation. xerox was clearly ahead of their time in the early 1980’s when they designed and developed the star office system. it was an elegant workstation with an iconic desktop developed by the engineers at parc (palo alto research center). the star office system offered functionality that neither microsoft nor apple has been able to match with their current offerings. the engineers developed star on a proprietary dev...
Describing microformats in JavaScript - Archive of obsolete content
fied. this allows an address to be marked as being, for example, a work address for receiving parcels. the street-address property is plural as well. this allows multiple lines of address information to be contained in the street-address array. the microformat is registered with the microformat api by calling microformats.add(), like this: microformats.add("adr", adr_definition); note: to be clear: since the adr microformat is included by default in firefox 3 and later, you don't need to add it yourself if you wish to make use of it. see also using microformats, parsing microformats in javascript ...
Displaying a graphic with audio samples - Archive of obsolete content
t = event.time, /* unused, but it's there */ signal = new float32array(fb.length / channels), magnitude; for (var i = 0, fbl = framebufferlength / 2; i < fbl; i++ ) { // assuming interlaced stereo channels, // need to split and merge into a stero-mix mono signal signal[i] = (fb[2*i] + fb[2*i+1]) / 2; } // clear the canvas before drawing spectrum ctx.fillstyle = "rgb(0,0,0)"; ctx.fillrect (0,0, canvas.width, canvas.height); ctx.fillstyle = "rgb(255,255,255)"; for (var i = 0; i < signal.length; i++ ) { // multiply spectrum by a zoom value magnitude = signal[i] * 1000; // draw rectangle bars for each frequency bin ctx.fillrect(i * ...
Archive of obsolete content
ones included in the popup menu. an interview with douglas bowman of wired news one of the web's oldest news sites, wired news draws between 20 and 25 million page views every month. on october 11, 2002, wired launched a brand-new site design that uses validating xhtml for its structure and a small collection of css files for its layout. the new design clearly shows what some experts have been saying: that standards-based design can be visually compelling and preserve the interface conventions we've come to expect from web pages. api archived documentation about obsolete web standards apis. archived mozilla and build documentation these articles are archived, obsolete documents about mozilla, gecko, a...
Anatomy of a video game - Game development
t the artillery blog for artillery games, where they adjust their rate of garbage generation to optimize garbage collection. obviously, cleaning up resources is not time sensitive (especially if tidying is more disruptive than the garbage itself). this may also apply to some of your own tasks. those are good candidates to throttle when available resources become a concern. summary i want to be clear that any of the above, or none of them, could be best for your game. the correct decision entirely depends on the trade-offs that you are willing (and unwilling) to make. the concern is mostly with switching to another option. fortunately, i do not have any experience with this, but i have heard it is an excruciating game of whack-a-mole. an important thing to remember for managed platforms, lik...
Unconventional controls - Game development
erticaldegree + '° <br />' + ' strength: ' + grabstrength + ''; } }); the code above is calculating and assigning the horizontaldegree, verticaldegree and grabstrength values that we will use later on, and outputting it in html so we can see the actual values. when those variables are up-to-date, we can use them in the draw() function to move the ship: function draw() { ctx.clearrect(0, 0, canvas.width, canvas.height); // ... if(horizontaldegree > degreethreshold) { playerx -= 5; } else if(horizontaldegree < -degreethreshold) { playerx += 5; } if(verticaldegree > degreethreshold) { playery += 5; } else if(verticaldegree < -degreethreshold) { playery -= 5; } if(grabstrength == 1) { alert('boo...
Efficient animation for web games - Game development
...
Build the brick field - Game development
add the following just above the drawball() call: drawbricks(); compare your code at this point, the game has got a little more interesting again : exercise: try changing the number of bricks in a row or a column, or their positions. next steps so now we have bricks! but the ball isn't interacting with them at all — we'll change that as we cont...
Track the score and win - Game development
the document.location.reload() function reloads the page and starts the game again once the alert button is clicked. compare your code t...
Visual typescript game engine - Game development
node.js is the best options. for email staff, i choose: npm i gmail-send. -run services database server (locally and leave it alive to develop process): npm run dataserver looks like this : mongod --dbpath ./server/database/data fix: "failed: address already in use" : netstat -ano | findstr :27017 taskkill /pid typeyourpidhere /f also important "run visual studio code as admini...
Gecko FAQ - Gecko Redirect 1
orking library (necko) platform-specific graphics rendering and widget sets for win32, x, and mac user preferences library mozilla plug-in api (npapi) to support the navigator plug-in interface open java interface (oji), with sun java 1.2 jvm rdf back end font library security library (nss) original document information author(s): angus other contributors: ekrock, vidur, hidday, drunclear copyright information: portions of this content are © 1998–2006 by individual mozilla.org contributors; content available under a creative commons license ...
ALPN - MDN Web Docs Glossary: Definitions of Web-related terms
...
Cipher - MDN Web Docs Glossary: Definitions of Web-related terms
ciphers were common long before the information age (e.g., substitution ciphers, transposition ciphers, and permutation ciphers), but none of them were cryptographically secure except for the one-time pad. modern ciphers are designed to withstand attacks discovered by a cryptanalyst. there is no guarantee that all attack methods have been discovered, but each algorithm is judged against known classes of attacks. ciphers operate two ways, either as block ciphers on successive blocks, or buffers, of data, or as stream ciphers on a continuous data flow (often of sound or video). ...
Ciphertext - MDN Web Docs Glossary: Definitions of Web-related terms
in cryptography, a ciphertext is a scrambled message that conveys information but is not legible unless decrypted with the right cipher and the right secret (usually a key), reproducing the original cleartext. a ciphertext's security, and therefore the secrecy of the contained information, depends on using a secure cipher and keeping the key secret. learn more general knowledge ciphertext on wikipedia ...
Decryption - MDN Web Docs Glossary: Definitions of Web-related terms
decryption is a cryptographic primitive: it transforms a ciphertext message into plaintext using a cryptographic algorithm called a cipher. like encryption, decryption in modern ciphers is performed using a specific algorithm and a secret, called the key. since the algorithm is often public, the key must stay secret if the encryption stays secure. decryption is the reverse of encryption and if the key stays secret, decryption without knowing the specific secret, decryption is mathematically hard to perform. how hard depends on the security of the cryptographic algorithm chosen and evolves with the progress of cryptanalysis. ...
Encryption - MDN Web Docs Glossary: Definitions of Web-related terms
a ciphertext is intended to be unreadable by unauthorized readers. encryption is a cryptographic primitive: it transforms a plaintext message into a ciphertext using a cryptographic algorithm called a cipher. encryption in modern ciphers is performed using a specific algorithm and a secret, called the key. since the algorithm is often public, the key must stay secret if the encryption stays secure. without knowing the secret, the reverse operation, decryption, is mathematically hard to perform. how hard depends on the security of the cryptographic algorithm chosen and evolves with the progress of cryptanalysis. ...
IDL - MDN Web Docs Glossary: Definitions of Web-related terms
, you read or set values of the desired type, so input.maxlength is always going to return a number and when you set input.maxlength ,it wants a number. if you pass another type, it is automatically converted to a number as specified by the standard javascript rules for type conversion. idl attributes can reflect other types such as unsigned long, urls, booleans, etc. unfortunately, there are no clear rules and the way idl attributes behave in conjunction with their corresponding content attributes depends on the attribute. most of the time, it will follow the rules laid out in the specification, but sometimes it doesn't. html specifications try to make this as developer-friendly as possible, but for various reasons (mostly historical), some attributes behave oddly (select.size, for example) a...
Object reference - MDN Web Docs Glossary: Definitions of Web-related terms
a link to an object. object references can be used exactly like the linked objects. the concept of object references becomes clear when assigning the same object to more than one property. rather than holding a copy of the object, each assigned property holds object references that link to the same object, so that when the object changes all properties referring to the object reflect the change. learn more general knowledge reference (computer science) on wikipedia ...
Plaintext - MDN Web Docs Glossary: Definitions of Web-related terms
plaintext refers to information that is being used as an input to an encryption algorithm, or to ciphertext that has been decrypted. it is frequently used interchangeably with the term cleartext, which more loosely refers to any information, such as a text document, image, etc., that has not been encrypted and can be read by a human or computer without additional processing. ...
Unicode - MDN Web Docs Glossary: Definitions of Web-related terms
bols. 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 like £, then you've seen this problem, known as mojibake. the most common unicode character encoding on the web is utf-8. other encod...
Assessment: Accessibility troubleshooting - Learn web development
trol the show/hide comment control button is not current keyboard-accessible. can you make it keyboard accessible, both in terms of focusing it using the tab key, and activating it using the return key? the table the data table is not currently very accessible — it is hard for screenreader users to associate data rows and columns together, and the table also has no kind of summary to make it clear what it shows. can you add some features to your html to fix this problem? other considerations? can you list two more ideas for improvements that would make the website more accessible? assessment or further help if you would like your work assessed, or are stuck and want to ask for help: put your work into an online shareable editor such as codepen, jsfiddle, or glitch. write a post ask...
WAI-ARIA basics - Learn web development
here. you can get an idea of support levels by looking at powermapper's wai-aria screen reader compatibility article. in this article, we won't attempt to cover every wai-aria feature, and its exact support details. instead, we will cover the most critical wai-aria features for you to know about; if we don't mention any support details, you can assume that the feature is well-supported. we will clearly mention any exceptions to this. note: some javascript libraries support wai-aria, meaning that when they generate ui features like complex form controls, they add aria attributes to improve the accessibility of those features. if you are looking for a 3rd party javascript solution for rapid ui development, you should definitely consider the accessibility of its ui widgets as an important fact...
What is accessibility? - Learn web development
notes designing with cognitive accessibility will lead to good design practices. they will benefit everyone. many people with cognitive impairments also have physical disabilities. websites must conform with the w3c’s web content accessibility guidelines, including cognitive accessibility guidelines. the w3c’s cognitive and learning disabilitie...
Cascade and inheritance - Learn web development
selectors are competing over the styling of the link's text color — the second one wins and makes the text white because although it has one less element selector, the missing selector is swapped out for a class selector, which is worth ten rather than one. so the winning specificity is 113 vs. 104. selectors 5–7 are competing over the styling of the link's border when hovered. selector six clearly loses to five with a specificity of 23 vs. 24 — it has one fewer element selectors in the chain. selector seven, however, beats both five and six — it has the same number of sub-selectors in the chain as five, but an element has been swapped out for a class selector. so the winning specificity is 33 vs. 23 and 24. note: this has only been an approximate example for ease of understandi...
Handling different text directions - Learn web development
nd the fact that some things display as block elements and others as inline elements. as we have seen described above, block and inline is tied to the writing mode of the document, and not the physical screen. blocks are only displayed from the top to the bottom of the page if you are using a writing mode that displays text horizontally, such as english. if we look at an example this will become clearer. in this next example i have two boxes that contain a heading and a paragraph. the first uses writing-mode: horizontal-tb, a writing mode that is written horizontally and from the top of the page to the bottom. the second uses writing-mode: vertical-rl; this is a writing mode that is written vertically and from right to left. when we switch the writing mode, we are changing which direction i...
Flexbox - Learn web development
become flex items. the result of this should be something like so: so, this single declaration gives us everything we need — incredible, right? we have our multiple column layout with equal sized columns, and the columns are all the same height. this is because the default values given to flex items (the children of the flex container) are set up to solve common problems such as this. to be clear, let's reiterate what is happening here. the element we've given a display value of flex to is acting like a block-level element in terms of how it interacts with the rest of the page, but its children are being laid out as flex items — the next section will explain in more detail what this means. note also that you can use a display value of inline-flex if you wish to lay out an element's ch...
Test your skills: floats - Learn web development
you will be working through three small tasks which use different elements of the material you have just covered. note: you can try out solutions in the interactive editors below, however it may be helpful to download the code and use an online tool such as codepen, jsfiddle, or glitch to work on the tasks. if you get stuck, then ask us for help — see the assessment or further help section at the bottom of this page. floats one in this task you need to float the two elements with a class of float1 and float2 left and right respectively. ...
Practical positioning examples - Learn web development
e panels the next job is to style our panels. let's get going! first, of all, add the following rule to style the .panels <div> container. here we simply set a fixed height to make sure the panels fit snugly inside the info-box, position relative to set the <div> as the positioning context, so you can then place positioned child elements relative to it and not the <html> element, and finally we clear the float set in the css above so that it doesn't interfere with the remainder of the layout. .info-box .panels { height: 352px; position: relative; clear: both; } finally for this section, we will style the individual <article> elements that comprise our panels. the first rule we'll add will absolutely position the panels, and make them all sit flush to the top and left of their <div> co...
How do you make sure your website works properly? - Learn web development
of the file path, and if there's still a problem, upload your files again. that will likely fix the problem. javascript errors someone (possibly you) added a script to the page and made a mistake. this will not prevent the page from loading but you will feel something went wrong. open the console (tools ➤ web developer ➤ web console) and reload the page: in this example, we learn (quite clearly) what the error is, and we can go fix it (we will cover javascript in another series of articles). more things to check we have listed a few simple ways to check that your website works properly, as well as the most common errors you may run across and how to fix them. you can also test if your page meets these criteria: how's the performance? does the page load fast enough? resources like ...
How much does it cost to do something on the Web? - Learn web development
postal address and email address behind their own addresses: the postal address can be provided in care of the registrar, and your email address can be obscured via your registrar's alias. do-it-yourself hosting vs. “packaged” hosting when you want to publish a website, you could do everything by yourself: set up a database (if needed), content management system, or cms (like wordpress, dotclear, spip, etc.), upload pre-made or your own templates. you could use your hosting provider's environment, for roughly ten to fifteen dollars per month, or subscribe directly to a dedicated hosting service with pre-packaged cmss (e.g., wordpress, tumblr, blogger). for the latter, you won't have to pay anything, but you may have less control over templating and other options. free hosting vs. paid ...
What is the difference between webpage, website, web server, and search engine? - Learn web development
earch engines are a common source of confusion on the web. a search engine is a special kind of website that helps users find web pages from other websites. there are plenty out there: google, bing, yandex, duckduckgo, and many more. some are generic, some are specialized about certain topics. use whichever you prefer. many beginners on the web confuse search engines and browsers. let's make it clear: a browser is a piece of software that retrieves and displays web pages; a search engine is a website that helps people find web pages from other websites. the confusion arises because, the first time someone launches a browser, the browser displays a search engine's homepage. this makes sense, because, obviously, the first thing you want to do with a browser is to find a web page to display. don...
What are browser developer tools? - Learn web development
what css is applied to each element on the page. it also allows you to instantly modify the html and css and see the results of your changes reflected live in the browser viewport. if you don't see the inspector, tap/click the inspector tab. in internet explorer, tap/click dom explorer, or press ctrl + 1. in microsoft edge, or opera, tap/click elements. in safari, the controls are not so clearly presented, but you should see the html if you haven't selected something else to appear in the window. press the style button to see the css. exploring the dom inspector for a start, right-click (ctrl-click) an html element in the dom inspector and look at the context menu. the available menu options vary among browsers, but the important ones are mostly the same: delete node (sometimes...
What are hyperlinks? - Learn web development
nies naturally want their sites to rank highly in search results. we know the following about how search engines determine a site's rank: a link's visible text influences which search queries will find a given url. the more incoming links a webpage can boast of, the higher it ranks in search results. external links influence the search ranking both of source and target webpages, but it is unclear by how much. seo (search engine optimization) is the study of how to make websites rank highly in search results. improving a website's use of links is one helpful seo technique. next steps now you'll want to set up some webpages with links. to get some more theoretical background, learn about urls and their structure, since every link points to a url. want something a bit more practical?
What is a URL? - Learn web development
issing parts of any url available inside that document. we can differentiate 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 ur...
What is a Domain Name? - Learn web development
, two, three...), separated by dots and read from right to left: each of those parts provides specific information about the whole domain name. tld (top-level domain). tlds tell users the general purpose of the service behind the domain name. the most generic tlds (.com, .org, .net) don't require web services to meet any particular criteria, but some tlds enforce stricter policies so it is clearer what their purpose is. for example: local tlds such as .us, .fr, or .se can require the service to be provided in a given language or hosted in a certain country — they are supposed to indicate a resource in a particular language or country. tlds containing .gov are only allowed to be used by government departments. the .edu tld is only for use by educational and academic institutions...
What is a web server? - Learn web development
textual all commands are plain-text and human-readable. stateless neither the server nor the client remember previous communications. for example, relying on http alone, a server can't remember a password you typed or remember your progress on an incomplete transaction. you need an application server for tasks like that. (we'll cover that sort of technology in other articles.) http provides clear rules for how a client and server communicate. we'll cover http itself in a technical article later. for now, just be aware of these things: only clients can make http requests, and then only to servers. servers can only respond to a client's http request. when requesting a file via http, clients must provide the file's url. the web server must answer every http request, at least with an err...
How to build custom form controls - Learn web development
e 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 <select> element. here is the result we want to achieve: this screenshot shows the three main states of our control: the normal state (on the left); the active stat...
How to structure a web form - Learn web development
o include the aria-label attribute, which is always read by screen readers. the above variants increase in effectiveness as you go through them: in the first example, the label is not read out at all with the input — you just get "edit text blank", plus the actual labels are read out separately. the multiple <label> elements confuse the screenreader. in the second example, things are a bit clearer — the label read out along with the input is "name star name edit text required", and the labels are still read out separately. things are still a bit confusing, but it's a bit better this time because the <input> has a label associated with it. the third example is best — the actual label is read out all together, and the label read out with the input is "name required edit text". note...
HTML basics - Learn web development
very</strong> grumpy.</p> you do however need to make sure that your elements are properly nested. in the example above, we opened the <p> element first, then the <strong> element; therefore, we have to close the <strong> element first, then the <p> element. the following is incorrect: <p>my cat is <strong>very grumpy.</p></strong> the elements have to open and close correctly so that they are clearly inside or outside one another. if they overlap as shown above, then your web browser will try to make the best guess at what you were trying to say, which can lead to unexpected results. so don't do it! empty elements some elements have no content and are called empty elements. take the <img> element that we already have in our html page: <img src="images/firefox-icon.png" alt="my test image...
Add a hitmap on top of an image - Learn web development
accessibility ramifications. text links (perhaps styled with css) are preferable to image maps for several reasons: text links are lightweight, maintainable, often more seo-friendly, and support accessibility needs (e.g., screen readers, text-only browsers, translation services). how to insert an image map, properly step 1: the image not just any image is acceptable. the image must make it clear what happens when people follow image links. alt text is mandatory, of course, but many people never see it. the image must clearly indicate where hotspots begin and end. hotspots must be large enough to tap comfortably, at any viewport size. how large is large enough? 72 × 72 css pixels is a good minimum, with additional generous gaps between touch targets. the map of the world at 50languages...
Define terms with HTML - Learn web development
with how to create a basic html document. objective: learn how to introduce new keywords and how to build description lists. when you need a term defined, you probably go straight to a dictionary or glossary. dictionaries and glossaries formally associate keywords with one or more descriptions, as in this case: blue (adjective) of a color like the sky in a sunny day. the clear blue sky of a subtle sadness, melancholy. i'm feeling blue but we're constantly defining keywords informally, as here: firefox is the web browser created by the mozilla foundation. to deal with these use cases, html provides tags to mark descriptions and words described, so that your meaning gets across properly to your readers. how to mark informal description in textbooks, the first ...
Debugging HTML - Learn web development
inutes to review discover browser developer tools. in the dom inspector, you can see what the rendered markup looks like: using the dom inspector, let's explore our code in detail to see how the browser has tried to fix our html errors (we did the review in firefox; other modern browsers should give the same result): the paragraphs and list items have been given closing tags. ...
Getting started with HTML - Learn web development
: creating your first html element edit the line below in the input area by wrapping it with the tags <em> and </em>. to open the element, put the opening tag <em> at the start of the line. to close the element, put the closing tag </em> at the end of the line. doing this should give the line italic text formatting! see your changes update live in the output area. if you make a mistake, you can clear your work using the reset button. if you get really stuck, press the show solution button to see the answer. playable code <h2>live output</h2> <div class="output" style="min-height: 50px;"> </div> <h2>editable code</h2> <p class="a11y-label">press esc to move focus away from the code area (tab inserts a tab character).</p> <textarea id="code" class="playable-code" style="min-height: 100px;w...
HTML text fundamentals - Learn web development
code textarea.onkeyup = function(){ // we only want to save the state when the user code is being shown, // not the solution, so that solution is not saved over the user code if(solution.value === 'show solution') { userentry = textarea.value; } else { solutionentry = textarea.value; } updatecode(); }; italic, bold, underline... the elements we've discussed so 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, semanti...
Images in HTML - Learn web development
ut there is a problem here: there is nothing that semantically links the image to its caption, which can cause problems for screen readers. for example, when you have 50 images and captions, which caption goes with which image? a better solution, is to use the html5 <figure> and <figcaption> elements. these are created for exactly this purpose: to provide a semantic container for figures, and to clearly link the figure to the caption. our above example could be rewritten like this: <figure> <img src="images/dinosaur.jpg" alt="the head and torso of a dinosaur skeleton; it has a large head with long sharp teeth" width="400" height="341"> <figcaption>a t-rex on display in the manchester university museum.</figcaption> </figure> the <figcaption> element tell...
From object to iframe — other embedding technologies - Learn web development
antage of web technologies instead. broaden your reach to everyone. everyone has a browser, but plugins are increasingly rare, especially among mobile users. since the web is easily used without any plugins, people would rather just go to your competitors' websites than install a plugin. give yourself a break from the extra accessibility headaches that come with flash and other plugins. stay clear of additional security hazards. adobe flash is notoriously insecure, even after countless patches. in 2015, alex stamos, then-chief security officer at facebook, requested that adobe discontinue flash. note: due to its inherent issues and the lack of support for flash, adobe announced that they would stop supporting it at the end of 2020. as of january 2020, most browsers block flash content...
Video and audio content - Learn web development
ation about this in our trackevent documentation. displaying video text tracks now we'll discuss a slightly more advanced concept that is really useful to know about. many people can't or don't want to hear the audio/video content they find on the web, at least at certain times. for example: many people have auditory impairments (such as being hard of hearing or deaf) so can't hear the audio clearly if at all. others may not be able to hear the audio because they are in noisy environments (like a crowded bar when a sports game is being shown). similarly, in environments where having the audio playing would be a distraction or disruption (such as in a library or when a partner is trying to sleep), having captions can be very useful. people who don't speak the language of the video might ...
HTML table advanced features and accessibility - Learn web development
f our timetable-fixed.html file. add a suitable caption for the table. save your code and open it in a browser to see what it looks like. note: you can find our version on github — see timetable-caption.html (see it live also). adding structure with <thead>, <tfoot>, and <tbody> as your tables get a bit more complex in structure, it is useful to give them more structural definition. one clear way to do this is by using <thead>, <tfoot>, and <tbody>, which allow you to mark up a header, footer, and body section for the table. these elements don't make the table any more accessible to screenreader users, and don't result in any visual enhancement on their own. they are however very useful for styling and layout — acting as useful hooks for adding css to your table. to give you some i...
HTML table basics - Learn web development
Learn › HTML › Tables › Basics
nts surrounding the table headers into <th> elements. save your html and load it in a browser, and you should see that the headers now look like headers. note: you can find our finished example at dogs-table-fixed.html on github (see it live also). why are headers useful? we have already partially answered this question — it is easier to find the data you are looking for when the headers clearly stand out, and the design just generally looks better. note: table headings come with some default styling — they are bold and centered even if you don't add your own styling to the table, to help them stand out. tables headers also have an added benefit — along with the scope attribute (which we'll learn about in the next article), they allow you to make tables more accessible by assoc...
Graceful asynchronous programming with Promises - Learn web development
ow we want. in a real app, your .catch() block could retry fetching the image, or show a default image, or prompt the user to provide a different image url, or whatever. note: you can see our version of the example live (see the source code also). chaining the blocks together this is a very longhand way of writing this out; we've deliberately done this to help you understand what is going on clearly. as shown earlier on in the article, you can chain together .then() blocks (and also .catch() blocks). the above code could also be written like this (see also simple-fetch-chained.html on github): fetch('coffee.jpg') .then(response => { if (!response.ok) { throw new error(`http error! status: ${response.status}`); } else { return response.blob(); } }) .then(myblob => { let obj...
Function return values - Learn web development
so it can be stored in a variable; and you can use this variable in the next stage of the calculation. using return values in your own functions to return a value from a custom function, you need to use the return keyword. we saw this in action recently in our random-canvas-circles.html example. our draw() function draws 100 random circles somewhere on an html <canvas>: function draw() { ctx.clearrect(0, 0, width, height); for (let i = 0; i < 100; i++) { ctx.beginpath(); ctx.fillstyle = 'rgba(255,0,0,0.5)'; ctx.arc(random(width), random(height), random(50), 0, 2 * math.pi); ctx.fill(); } } inside each loop iteration, three calls are made to the random() function, to generate a random value for the current circle's x-coordinate, y-coordinate, and radius, respectively. t...
Test your skills: Functions - Learn web development
you need to create 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 th...
A first splash into JavaScript - Learn web development
uesses paragraph, plus a blank space so there will be a space between each guess shown. the next block (lines 8–24 above) does a few checks: the first if(){ } checks whether the user's guess is equal to the randomnumber set at the top of our javascript. if it is, the player has guessed correctly and the game is won, so we show the player a congratulations message with a nice green color, clear the contents of the low/high guess information box, and run a function called setgameover(), which we'll discuss later. now we've chained another test onto the end of the last one using an else if(){ } structure. this one checks whether this turn is the user's last turn. if it is, the program does the same thing as in the previous block, except with a game over message instead of a congratulat...
JavaScript object basics - Learn web development
on2.greeting() on the other hand outputs "hi! i'm deepti.", even though the method's code is exactly the same in each case. as we said earlier, this is equal to the object the code is inside — this isn't hugely useful when you are writing out object literals by hand, but it really comes into its own when you are dynamically generating objects (for example using constructors). it will all become clearer later on. you've been using objects all along as you've been going through these examples, you have probably been thinking that the dot notation you've been using is very familiar. that's because you've been using it throughout the course! every time we've been working through an example that uses a built-in browser api or javascript object, we've been using objects, because such features are...
Object-oriented JavaScript for beginners - Learn web development
ject() constructor as a parameter, to prefill it with properties/methods. try this in your js console: let person1 = new object({ name: 'chris', age: 38, greeting: function() { alert('hi! i\'m ' + this.name + '.'); } }); using the create() method constructors can help you give your code order—you can create constructors in one place, then create instances as needed, and it is clear where they came from. however, some people prefer to create object instances without first creating constructors, especially if they are creating only a few instances of an object. javascript has a built-in method called create() that allows you to do that. with it, you can create a new object based on any existing object. with your finished exercise from the previous sections loaded in the b...
Object prototypes - Learn web development
ween an object's prototype (available via object.getprototypeof(obj), or via the deprecated __proto__ property) and the prototype property on constructor functions. the former is the property on each instance, and the latter is the property on the constructor. that is, object.getprototypeof(new foobar()) refers to the same object as foobar.prototype. let's look at an example to make this a bit clearer. understanding prototype objects here we'll go back to the example in which we finished writing our person() constructor — load the example in your browser. you can use our oojs-class-further-exercises.html example (see also the source code), if you don't already have it from working through the last article. in this example, we have defined a constructor function, like so: function perso...
The business case for web performance - Learn web development
previous overview: performance we've discussed the importance of web performance. you've learned what you need to do to optimize for web performance. but how do you convince your clients and/or management to prioritize and invest in performance? in this section, we discuss creating a clear business-case to convince decision-makers to make the investment. prerequisites: basic computer literacy, basic knowledge of client-side web technologies, and a basic understanding of web performance optimization. objective: to gain confidence in working with clients and management to get them to make web performance a priority. making performance a business priority we've discussed how prioritizing performance can improve user experience and therefore revenue. we...
Introduction to the server side - Learn web development
feed and look at the stream of posts. note how some of the posts are out of numerical order - in particular, posts with more "likes" are often higher on the list than more recent posts. also look at what kind of ads you are being shown — you might see ads for things you looked at on other sites. facebook's algorithm for highlighting content and advertising can be a bit of a mystery, but it is clear that it does depend on your likes and viewing habits! summary congratulations, you've reached the end of the first article about server-side programming. you've now learned that server-side code is run on a web server and that its main role is to control what information is sent to the user (while client-side code mainly handles the structure and presentation of that data to the user). you ...
Server-side web frameworks - Learn web development
the main websites for django (python) and express (node/javascript) and check out their documentation and community. navigate to the main sites (linked above) click on the documentation menu links (named things like "documentation, guide, api reference, getting started", etc.). can you see topics showing how to set up url routing, templates, and databases/models? are the documents clear? navigate to mailing lists for each site (accessible from community links). how many questions have been posted in the last few days how many have responses? do they have an active community? a few good web frameworks? let's now move on, and discuss a few specific server-side web frameworks. the server-side frameworks below represent a few of the most popular available...
Getting started with Ember - Learn web development
building apps that desire either or both of the following traits: single page applications, including native-like web apps, and progressive web apps (pwas) ember works best when it is the entire front end of your application. increasing cohesion among many team's technology stacks community-backed "best practices" allow for faster long-term development speed. ember has clear conventions that are useful for enforcing consistency and helping team members get up to speed quickly. ember with add-ons emberjs has a plugin architecture, which means that add-ons can be installed and provide additional functionality without much, if any, configuration. examples include: prember: static website rendering for blogs or marketing content. fastboot: server-side render...
Framework main features - Learn web development
pt, but not the other way around. typescript is useful for the strictness it allows developers to enforce on their code. for instance, consider a function add(), which takes integers a and b and returns their sum. in javascript, that function could be written like this: function add(a, b) { return a + b; } this code might be trivial for someone accustomed to javascript, but it could still be clearer. javascript lets us use the + operator to concatenate strings together, so this function would technically still work if a and b were strings — it just might not give you the result you'd expect. what if we wanted to only allow numbers to be passed into this function? typescript makes that possible: function add(a: number, b: number) { return a + b; } the : number written after each param...
React interactivity: Events and state - Learn web development
console.log() to setname(), as shown below: function handlechange(e) { setname(e.target.value); } now we need to change our handlesubmit() function so that it calls props.addtask with name as an argument — remember our callback prop? this will serve to send the task back to the app component, so we can add it to our list of tasks at some later date. as a matter of good practice, you should clear the input after your form submits, so we'll call setname() again with an empty string to do so: function handlesubmit(e) { e.preventdefault(); props.addtask(name); setname(""); } at last, you can type something into the input field in your browser and click add — whatever you typed will appear in an alert dialog. your form.js file should now read like this: import react, { usestate } ...
Beginning our React todo list - Learn web development
height: 4.4rem; padding: 0.4rem 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; disp...
Starting our Svelte Todo list app - Learn web development
height: 4.4rem; padding: 0.4rem 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; disp...
TypeScript support in Svelte - Learn web development
, ms) => { ./svelte-todo-typescript/src/components/alert.svelte:11:37 warn: parameter 'ms' implicitly has an 'any' type, but a better type may be inferred from usage. (ts) (message, ms) => { you can fix these by specifying the corresponding types, like so: export let ms = 3000 let visible: boolean let timeout: number const onmessagechange = (message: string, ms: number) => { cleartimeout(timeout) if (!message) { // hide alert if message is empty note: there's no need to specify the ms type with export let ms:number = 3000 because typescript is already inferring it from its default value. moreactions.svelte now we'll do the same for the moreactions.svelte component. add the lang='ts' attribute, like before. typescript will warn us about th...
Componentizing our Svelte app - Learn web development
ng the repl, start at https://svelte.dev/repl/99b9eb228b404a2f8c8959b22c0a40d3?version=3.23.2 breaking the app into components in svelte, an application is composed from one or more components. a component is a reusable, self-contained block of code that encapsulates html, css and javascript that belong together, written into a .svelte file. components can be big or small, but they are usually clearly defined: the most effective components serve a single, obvious purpose. the benefits of defining components are comparable to the more general best practice of organizing your code into manageable pieces. it will help you understand how they relate to each other, it will promote reuse, and it will make your code easier to reason about, maintain, and extend. but how do you know what should be ...
Getting started with Svelte - Learn web development
dern tooling ecosystem. svelte sticks closely to the classic web development model of html, css, and js, just adding a few extensions to html and javascript. it arguably has fewer concepts and tools to learn than some of the other framework options. it's main current disadvantages are that it is a young framework — its ecosystem is therefore more limited in terms of tooling, support, plugins, clear usage patterns, etc. than 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 introduct...
Dynamic behavior in Svelte: working with variables and props - Learn web development
o). this would work, but now svelte has no way to find out that {#each filtertodos(todos)... } depends on filter, and the list of filtered todos won't be updated when the filter changes. always remember that svelte analyzes our code to find out dependencies, so it's better to be explicit about it and not rely on the visibility of top-level variables. besides, it's a good practice to make our code clear and explicit about what information it is using. the code so far git to see the state of the code as it should be at the end of this article, access your copy of our repo like this: cd mdn-svelte-tutorial/04-componentizing-our-app or directly download the folder's content: npx degit opensas/mdn-svelte-tutorial/04-componentizing-our-app remember to run npm install && npm run dev to start y...
Vue conditional rendering: editing existing todos - Learn web development
been successfully listened for. yes, this is a chain of two different item-edit events! result: edittodo() method invoked to update label of associated todo item. todoform.vue <form> listens for submit event. result: onsubmit() method is invoked, which checks that the new label is not empty, then emits the todo-added event (which is then listened for inside app.vue, see above), and finally clears the new label <input>. todoitem.vue checkbox <input> listens for change event. result: checkbox-changed event emitted when the checkbox is checked/unchecked (which is then listened for inside app.vue; see above). "edit" <button> listens for click event. result: toggletoitemeditform() method is invoked, which toggles this.isediting to true, which in turn displays the todo item's edit form on...
Getting started with Vue - Learn web development
ata and an html-based template syntax that maps to the underlying dom structure. for installation, and to use some of the more advanced features of vue (like single file components or render functions), you'll need a terminal with node + npm installed. objective: to setup a local vue development environment, create a starter app, and understand the basics of how it works. a clearer vue vue is a modern javascript framework that provides useful facilities for progressive enhancement — unlike many other frameworks, you can use vue to enhance existing html. this lets you use vue as a drop-in replacement for a library like jquery. that being said, you can also use vue to write entire single page applications (spas). this allows you to create markup managed entirely by vue,...
Adding a new todo form: Vue events, methods, and models - Learn web development
ause we're using v-model to bind the data to the <input> in todoform, if we set the name parameter to equal an empty string, the input will update as well. update your todoform component’s onsubmit() method to this: onsubmit() { if(this.label === "") { return; } this.$emit('todo-added', this.label); this.label = ""; } now when you click the "add" button, the "new-todo-input" will clear itself. summary excellent. we can now add todo items to our form! our app is now starting to feel interactive, but one issue is that we've completely ignored its look and feel up to now. in the next article, we'll concentrate on fixing this, looking at the different ways vue provides to style components. previous overview: client-side javascript frameworks next in this module intro...
Focus management with Vue refs - Learn web development
uld immediately be moved to the edit <input>. handling focus when deleting to-do items there's one more place we need to consider focus management: when a user deletes a to-do. when clicking the "edit" button, it makes sense to move focus to the edit name text box, and back to the "edit" button when canceling or saving from the edit screen. however, unlike with the edit form, we don’t have a clear location for focus to move to when an element is deleted. we also need a way to provide assistive technology users with information that confirms that an element was deleted. we're already tracking the number of elements in our list heading — the <h2> in app.vue — and it's associated with our list of to-do items. this makes it a reasonable place to move focus to when we delete a node. first...
Styling Vue components with CSS - Learn web development
; appearance: none; } .custom-checkbox > input:focus { outline: 3px dashed #fd0; outline-offset: 0; box-shadow: inset 0 0 0 2px; } .custom-checkbox { 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: 40px; margin-bottom: 10px; padding-left: 40px; clear: left; } .custom-checkbox > input[type="checkbox"] { -webkit-font-smoothing: antialiased; 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: 8p...
Understanding client-side JavaScript frameworks - Learn web development
vice to keep track of the data state of our app. 4. ember interactivity: footer functionality, conditional rendering now it's time to start tackling the footer functionality in our app. here we'll get the todo counter to update to show the correct number of todos still to complete, and correctly apply styling to completed todos (i.e. where the checkbox has been checked). we'll also wire up our "clear completed" button. along the way, we'll learn about using conditional rendering in our templates. 5. routing in ember in this article we learn about routing or url-based filtering as it is sometimes referred to. we'll use it to provide a unique url for each of the three todo views — "all", "active", and "completed". 6. ember resources and troubleshooting our final ember article provides you...
Implementing feature detection - Learn web development
so here we're applying the top set of rules only to browsers that do support flexbox, and the bottom set of rules only to browsers that don't (no-flexbox). note: bear in mind that all of modernizr's ht...
Handling common HTML and CSS problems - Learn web development
</div> <div> <label for="time">enter a time:</label> <input id="time" type="time"> </div> </form> the output of this code is as follows: hidden example label { float: left; width: 30%; text-align: right; } input { float: right; width: 65%; } label, input { margin-bottom: 20px; } div { clear: both; margin: 10px; } body { width: 400px; margin: 0 auto; } <form> <div> <label for="date">enter a date:</label> <input id="date" type="date"> </div> <div> <label for="time">enter a time:</label> <input id="time" type="time"> </div> </form> note: you can also see this running live as for...
Handling common JavaScript problems - Learn web development
t will automatically generate bundles for you — see browserify (see getting started with browserify for a basic tutorial). it is a good idea to bundle js files into one like this — reducing the number of http requests you need to make improves the performance of your site. you can see this code in action in fetch-polyfill-only-when-needed.html (see the source code also). we'd like to make it clear that we can't take credit for this code — it was originally written by philip walton. check out his article loading polyfills only when needed for the original code, plus a lot of useful explanation around the wider subject). note: there are some 3rd party options to consider, for example polyfill.io — this is a meta-polyfill library that will look at each browser's capabilities and apply ...
Command line crash course - Learn web development
racters, 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 all and only dele...
Deploying our app - Learn web development
r an interactive process, or add individual files using git add path/to/file. now all the code is staged, we can commit; run the following command: git commit -m ’committing initial code’ note: although you're free to write whatever you wish in the commit message, there's some useful tips around the web on good commit messages. keep them short, concise, and descriptive, so they clearly describe what the change does. finally the code needs to be pushed to your github hosted repository. let's do that now. over at github, visit https://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 ...
Introducing a complete toolchain - Learn web development
ary installation tools — for adding dependencies. code revision control. code tidying tools — for tidying javascript, css, and html. code linting tools — for linting our code. library installation tools we'll use npm to install our tools, which you first met in chapter 2. you should have node.js and npm installed already, but if not, refer back to that section. note: though it's not clear 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" b...
Accessibility information for UI designers and developers
set word spacing to at least 0.16 times the font size this does not mean that your page needs to offer controls to make such changes, merely that if someone does these things in a custom stylesheet, they should not break the interface. forms in forms, provide labels for all controls. this includes form elements like inputs and select boxes, but also buttons. for form elements, it should be clear what kind of input is expected. placeholders are best avoided for this, as they are often too low in contrast. it is more helpful to describe what an input element is for in text just above or underneath the input. error recovery when you detect users provide unexpected input, explain what is wrong and, if possible, how to correct it. this is specifically important in these cases: the user i...
Mozilla’s UAAG evaluation report
note that the size might be discovered for certain resources using http head. however, any such use should be carefully considered, given the potential impact on network traffic of automatically making such requests for every link/object in the page. please see bug 103704 for more information. does not provide information about whether link is internal or external, except through url itself. clearly identifying internal vs. external links is bug 127038. provides information about whether link will open in same window does not support fee links 10.7 highlight current viewport. (p1) vg uses title bar color and focus indicator to indicate with view port has focus the currently focused content frame has a dotted outline, until a key is pressed or scrolling occurs...
Choosing the right memory allocator
d in the /security/ subtree of the source code. avoid using them elsewhere. ...
Command line options
r, if installed, and inspect the given url (where url is optional). -jsdebugger start application with browser toolbox (formerly browser debugger). that is different to venkman debugger (see option -venkman). -jsconsole start application with the error console, or, in firefox, the browser console. -purgecaches gecko (layout engine) has a javascript cache, which is not reset on startup, this clears it. -start-debugger-server port firefox only. start the debugger server on port. this will enable another instance of firefox to connect the firefox developer tools to this firefox instance. see the article on remotely debugging firefox desktop. the port argument is optional, and if it is omitted, the server will listen on port 6000. -venkman start with the javascript debugger, venkman, if ...
Debugging Frame Reflow
verflow the parent have the ns_frame_outside_children flag set. for these frames the overflow area is displayed as block 025ed8f0 d=8940,1020 o=(0,0) 9180 x 1020. the overflow area is specified as (x,y) origin and width x height. the reflow finishes at the same level where it started. advanced reflow debugging the previously described technique dumps the data for every frame. sometimes the log is clearer if only the main frames are shown. the entries in the reflow log can be controlled on a frame level. for instance adding text 0 to the rules in reflow_rules.txt would hide the text entries from the reflow. the display of the following frames can be turned on by adding a line with the frame name and 1 or turned off by adding a line with the frame name and 0: short name layou...
Contributing to the Mozilla code base
code review. who is the right person to ask for a review? if you have a mentored bug: ask your mentor. they will help, or can easily find out. it might be them! run hg blame on the file and look for the people who have touched the functions you're working on. they too are good candidates. running hg log and looking for regular reviewers might be a solution too. the bug itself may contain a clear indication of the best person to ask for a review are there related bugs on similar topics? the reviewer in those bugs might be another good choice we have a list of modules, which lists peers and owners for the module. some of these will be good reviewers. in a worst case scenario, set the module owner as the reviewer, asking them in the comments to pick someone more suitable please select o...
Displaying Places information using views
esult will in turn set the result property on the given nsinavhistoryresultobserver. you should not set the result property explicitly. to disconnect a viewer from its result, call removeobserver(view) on your result. be careful about reference cycles. the viewer and the result both hold owning references to each other. for these objects to be freed during javascript garbage collection, you must clear this cycle by calling result.removeobserver(view). (for example, the built-in tree view does this automatically. when the tree is destroyed or a different nsitreeview is associated with the tree, the tree will set the tree property of the old nsitreeview to null. because the object implementing nsitreeview also implements nsinavhistoryresultobserver, the viewer then disconnects itself from the re...
Performance best practices for Firefox front-end engineers
e a much higher probability of running at 60 fps (see the section below called use the compositor for animations for further details). perhaps you’re touching some dom nodes in such a way that unexpected repaints are occurring in an area that don’t need it. best to investigate and try to remove those as best you can. sometimes, our graphics layer invalidates regions in ways that might not be clear to you, and a section outside of the thing that just repainted will also repaint. sometimes this can be addressed by ensuring that the thing changing is on its own layer (though this comes at a memory cost). you can put something on its own layer by setting its z-index, or by setting the will-change on the node, though this should be used sparingly. if you’re unsure why something is repainting...
mozbrowserfindchange
o not use it on production sites facing the web: it will not work for every user. there may also be large incompatibilities between implementations and the behavior may change in the future. the mozbrowserfindchange event is fired when a search method is invoked in the browser <iframe> content. this includes htmliframeelement.findall(), htmliframeelement.findnext(), and htmliframeelement.clearmatch(). general info specification non standard interface customevent bubbles yes cancelable yes target <iframe> default action none properties property type description target read only eventtarget the browser iframe type read only domstring the type of event. bubbles read only boolean whether the event normally...
HTMLIFrameElement.purgeHistory()
syntax there is a domrequest version and a promise version: var mydomrequest = instanceofhtmliframeelement.purgehistory(); instanceofhtmliframeelement.purgehistory().then(function() { ... }); returns either a domrequest object that returns an onsuccess handler if the history is deleted, or an onerror handler if not. ...
HTML parser threading
on gets its start index restored to the index stored on the speculation object. subsequent buffers get their start index reset back to zero. the tokenizer gets its line number restored from the speculation object. this is equivalent to rewinding the input to where it was when speculation started. all the speculations in the speculation queue are destroyed. pending tree ops in the tree builder are cleared. the tree op stage is set as the tree op sink for the tree builder. the executor is told that it's reading from the stage again. the state of the main-thread tokenizer is copied to the parser-thread tokenizer. likewise for the tree builders. the "last was carriage return" flag is copied over also. a runnable is dispatched to the parser thread to call to mark the parser uninterrupted and to call...
Hacking with Bonsai
e 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 pool lane is only available to those who arrange access ahead of time with the release team. when the tree is re-opened, the web page is updated and the hook is cleared. use the bonsai query tool to see what's been checked in to the tree lately and to look at differences between versions. read the introduction to bonsai for more information about queries. the rules no checkins when the tree is closed unless you are fixing a build problem at the request of a build person. if you are on the hook, your top priority is to be available to the build team to fix bu...
How to implement a custom autocomplete search component
if you are using xulrunner please don't forget that changes will only take place when you either disable caching or run xulrunner with -purgecaches ...
IME handling guide
b application changes the content differently from cache in tsftextstore. however, tsftextstore ignores such fact temporarily until the composition is finished completely. the reason is that, notifying unexpected text or selection changes to tsf and/or tip during composition may behave them odd. when a composition is committed and it receives notify_ime_of_composition_event_handled, tsftextstore clears the cache of contents and notifying tsf of merged text changes and the last selection change if they are not caused by composition. by this step, tsf and tip may sync its internal cache with actual contents. note that if new composition is started before notify_ime_of_composition_event_handled notification, tsftextstore handles the new composition with cached contents which may be different fro...
Extending a Protocol
sync 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 phabricator - search for "pwindowglobal.ipdl". congrats! we've now set up the bi-directional relationship between pwindowglobal and pecho at the protocol level. we've told gecko who manages who, and what messages we want to send. now we actually need to implement the "echochild" and "echoparent" actors to handle sending and receiving m...
PBackground
ound-based actors and the processing, file i/o, etc, can be controlled from the pbackground thread regardless of where the dom calls are being made. the logic is all implemented in actorsparent.cpp and actorschild.cpp in the dom/indexeddb directory. these are not small files (actorsparent.cpp was over 27k lines of code as of this publication) but the logic that needs to run in the parent is very clearly separated from the dom code no matter what thread it's running on. note: this article was original published as what is pbackground?, by kyle huey. ...
Internationalized Domain Names (IDN) Support in Mozilla Browsers
commercial browser that has built-in support for internationalized domain name under the new ietf rfc's established in 2003. an internationalized domain name (idn) is a domain/host name which uses non-ascii characters. until recently domain names allowed only a subset of 7-bit ascii characters. as the internet has spread to non-english speaking people around the world, it has become increasingly clear that forcing them to use domain names written only in a subset of the latin alphabet is not ideal. many of the european languages use the basic latin alphabet with additional accented characters for writing but they were not able to use them in domain names. there are many languages whose writing scripts are not based on latin alphabet at all. speakers of these languages were not able to use fam...
CustomizableUI.jsm
ance, the window is in customization mode, or if this is an overflowable toolbar and the widget has been overflowed. parameters aarea the id of the area whose customize target you want to have awindow the window where you want to fetch the dom node. return value the customize target dom node for aarea in awindow reset() reset the customization state back to its default. this is the nuclear option. you should never call this except if the user explicitly requests it. firefox does this when the user clicks the "restore defaults" button in customize mode. undoreset() undoes a previous reset, restoring the state of the ui to the state prior to the reset. this can only be called immediately after reset(). if any of the ui is changed after calling reset(), then undoreset will be a no-o...
DownloadLastDir.jsm
owsing normally, the browser uses the browser.download.lastdir preference to store the last download directory path. however, when private browsing mode is enabled, the last download directory path is instead maintained in memory, and the preference is not changed. when the user exits private browsing mode, the last download directory value is reverted to the preference's value. when history is cleared when the user's browsing history is cleared, the value of the last download directory path is restored to the platform's default download directory path. ...
Sqlite.jsm
will be as privileged as the original connection. transactioninprogress this boolean property indicates whether a transaction is in progress. this is rarely needed by external callers. shrinkmemory() this function can be called to shrink the memory usage of the connection. this is a glorified wrapper around the 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 operati...
Webapps.jsm
getappbylocalid: function(alocalid) getmanifesturlbylocalid: function(alocalid) getapplocalidbymanifesturl: function(amanifesturl) getcoreappsbasepath: function() getwebappsbasepath: function() _islaunchable: function(aapp) _notifycategoryandobservers: function(subject, topic, data, msg) registerbrowserelementparentforapp: function(amsg, amn) receiveappmessage: function(appid, message) _clearprivatedata: function(appid, browseronly, msg) _sendprogressevent: function() updatestatechanged: function appobs_update(aupdate, astate) applicationcacheavailable: function appobs_cacheavail(aapplicationcache) ...
Mozilla Content Localized in Your Language
vailable line space. this allows localization text to expand and not be truncated or resolved through ellipsis. title on the final page (meaning no more click through) should allow enough room to display full text. buttons capitalize the first letter of each word. limit to one or two words. use verbs that precisely describe the button's action. for example, "cancel", "clear history", "add email", "select all", etc. value selector lists capitalize the first letter of the first word and the first letter of any proper nouns. limit to one or two words. note: if this doesn't apply to your language, indicate so as n/a. articles -- avoid them articles (such as the word "the" in english) should be avoided wherever po...
Localization and Plurals
s shown to the user. for example, "1 page" vs "2 pages". if you're here to make your code (e.g., extensions) localizable for plural forms, you can jump straight to developing with pluralform. you may also need to localize the initial strings for your code, so it would be good to read through at least the usage section as well. usage here are a couple terms used in this page to help keep things clear: plural rule: for a given language, there is a grammatical rule on how to change words, depending on the number qualifying the word. different languages can have different rules. plural form: for a particular plural rule, there can be multiple forms of a word, such as "page" and "pages". in this case, there are 2 forms, but other languages can have 1 or many more. if you're here for pluralr...
Localization content best practices
nce. a much more flexible solution would be: # localization note(tos-text): {{link}} will be replaced at run-time # by an active link. string with id 'tos-link' will be used as text # for this link. tos-text = by proceeding you accept the {{link}} tos-link = terms of services and then replace {{link}} at run-time with the second string. note also the localization comments and make sure it is clear to the localizer which placeholder string will appear in lieu of the placeholder as this may affect translation and/or inflection. for example, by proceeding you accept the {{terms of service}} will result in the gaelic translation ma leanas tu air adhart, bidh tu a' gabhail ri {{teirmichean na seirbheise}}. but in another grammatical context, {{terms of service}} may require a different inflecti...
Creating localizable web content
depending on context, find alternate strings or document an explanation of the string for localizers check that we don't link in new pages to sub-pages with anchors. ...
Using the viewport meta tag to control layout on mobile browsers
on such as viewport width on portrait and landscape orientation as well as physical screen size, operating system and the pixel density of the device. specifications specification status comment css device adaptationthe definition of '<meta name="viewport">' in that specification. working draft non-normatively describes the viewport meta element there is clearly demand for the viewport meta tag, since it is supported by most popular mobile browsers and used by thousands of web sites. it would be good to have a true standard for web pages to control viewport properties. as the standardization process proceeds, we at mozilla will work to keep up to date with any changes. ...
Mozilla Development Strategies
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 out and tackle daily regressions, you need to find a way to not let them affect you. you don't want to have one tree, update it every morning, and then be stuck waiting for blockers to clear. have multiple trees. at least one of them should be updated every day. you'll need this one for regressions that require your immediate attention (a new crasher, a blocker, or problem in your area, for example). use this same tree for small, quick bugs or recent regressions or crashers. for your other tree, don't update as often. update when you know that the tree is in good shape. do your prim...
Measuring performance using the PerfMeasurement.jsm code module
tomatically 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 properties: let report = "cpu cycles: " + monitor.cpu_cycles + "\n" + "cache refs: " + monitor.cache_references + "\n" + "cache misses: " + monitor.cache_misses + "\n"; monitor.reset(); alert(report); the reset() method clears all of the enabled counters, as you might expect. when you're done with your measurements, just let the monitor object go out of scope. ...
Memory Profiler
n. it can be obtained by installing the memory profiler add-on. you may need to set the "xpinstall.signatures.required" pref to false in order to install it, since the xpi is not yet signed. using the add-on open the devtools panel or webide. select the memoryprofiler tab. to take a profile you can use the buttons in the profiler panel. start - start profiling stop - stop profiling reset - clear profile data when profiler is stopped profile data is accumulated and resumed after start. use reset to start a new recording. understanding the profiles traditional memory analysis tools look at the data. they build the referring-to, namely retaining graphs. this is helpful in exploring the relationships among objects and identifying memory leaks. however, the information exposed in this...
Refcount tracing and balancing
object that corresponds to 0x00253ab0 in the new run, and run make-tree.pl. what we'd hope to see is a tree that looks like: .root: bal=0 main: bal=0 dosomethingwithfooandreturnittoo: bal=1 ns_newfoo: bal=1 that is, ns_newfoo() "leaks" a single reference count; this leak is "inherited" by dosomethingwithfooandreturnittoo(); but is finally balanced by a release() in main(). hints clearly, this is an iterative and analytical process. here are some tricks that make it easier. check for leaks from smart pointers. if the leak comes from a smart pointer that is logged in the xpcom_mem_comptr_log, then find-comptr-leakers.pl will find the exact stack for you, and you don't have to look at trees. ignore balanced trees. the make-tree.pl script accepts an option --ignore-balanced, whi...
Scroll-linked effects
ination - window.scrolly) < 3) { scrollto(window.scrollx, destination); } else if (math.abs(destination - window.scrolly) < 200) { scrollto(window.scrollx, window.scrolly + ((destination - window.scrolly) / 2)); settimeout(snap, 20, destination); } } var timeoutid = null; addeventlistener("scroll", function() { if (timeoutid) cleartimeout(timeoutid); timeoutid = settimeout(snap, 200, parseint(document.getelementbyid('snaptarget').style.top)); }, true); </script> <div id="snaptarget" class="snaptarget" style="position: relative; top: 200px; width: 100%; height: 200px; background-color: green"></div> </body> in this example, there is a scroll event listener which detects if the scroll position is within 200 pix...
about:memory
ch includes the browser tabs and ui windows. for example, the "top(http://edition.cnn.com/, id=8)" sub-tree represents the tab open to cnn.com, and "top(chrome://browser/content/browser.xul, id=3)" represents the main browser ui window. within each window's measurements are sub-trees for javascript ("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-...
dtrace
stack", i.e. the stack of the userspace program executing. run that command for a few seconds and then hit ctrl + c to interrupt it. dtrace will then print to the output file a number of stack traces, along with a wakeup count for each one. the ordering of the stack traces can be non-obvious, so look at them carefully. sometimes the stack trace has less information than one would like. it's unclear how to improve upon this. ...
perf
s <command> is executed once; higher values can be used to get variations. the output will look like the following. performance counter stats for 'system wide': 51.58 joules power/energy-pkg/ [100.00%] 14.80 joules power/energy-cores/ [100.00%] 9.93 joules power/energy-gpu/ [100.00%] 27.38 joules power/energy-ram/ [100.00%] 5.003049064 seconds time elapsed it's not clear from the output, but the following relationship holds. energy-pkg >= energy-cores + energy-gpu the measurement is in joules, which is usually less useful than watts. for these reasons rapl is usually a better tool for measuring power consumption on linux. wakeups perf can also be used to do high-context profiling of wakeups. ...
Phishing: a short definition
n security and privacy, suggests that the above countermeasures fail to protect the majority of users. this too, includes missing https or ev certificate indicators in a browser’s navigation bar. services assuming responsibility technical solutions can be more efficient if implemented to protect millions of users automatically. as most phishing attacks start with unsolicited email messages, a clear starting point is improving spam filters, thus reducing the number of fraudulent messages reaching users. web browser vendors too, are interested in protecting their users from phishing. after all, the browser plays an essential role in the scheme: a fake website is loaded in a browser and here is the maker’s last chance to preventing fraud. since version 2.0, firefox has used google’s safeb...
Leak Monitor
leak monitor is a firefox extension by l. david baron that helps extension and chrome developers to find memory leaks. it will pop-up an alert when a window is closed and javascript still links to that window (for example, an observer that is not cleared when the window closes). obtain the extension on amo (addons.mozilla.org) view more information on leak monitor on david baron's page ...
McCoy
mccoy is an application that allows add-on authors to provide secure updates to their users. applications periodically look for and install updates to their add-ons. it's important that the update information retrieved has not been tampered with since being written by the add-on author. specifically, it focuses on the process of digitally signing update manifests so the applications can verify the integrity of a manifest retrieved over normally insecure channels. ...
NSPR Contributor Guide
rs look like that. some guidelines concerning naming conventions can be found in nspr naming conventions in the nspr reference. see also: xxx ownership of your contribution when you contribute something to nspr, you must have intellectual property rights to that contribution. this means that you cannot give us something you snatched from somewhere else;. it must be your own invention, free and clear of encumberment of anyone or anything else; pay close attention to the rights of your "day-job" employer. if you snatched it from somewhere else, tell us where; show us where the right to incorporate it into nspr exists. license under mpl or gpl when you contribute material to nspr, you agree to allow your contribution to be licensed under the mpl or gpl. bugfixes use bugzilla to track bugs...
Introduction to NSPR
thread priorities the host operating systems supported by nspr differ widely in the mechanisms they use to support thread priorities. in general, an nspr thread of higher priority has a statistically better chance of running relative to threads of lower priority. however, because of the multiple strategies to provide execution vehicles for threads on various host platforms, priorities are not a clearly defined abstraction in nspr. at best they are intended to specify a preference with respect to the amount of cpu time that a higher-priority thread might expect relative to a lower-priority thread. this preference is still subject to resource availability, and must not be used in place of proper synchronization. for more information on thread synchronization, see nspr thread synchronization. t...
PLHashEnumerator
nhash 4 /* just unhash the current entry */ description plhashenumerator is a function type used in the enumerating a hash table. when all the table entries are enumerated, each entry is passed to a user-specified function of type plhashenumerator with the hash table entry, an integer index, and an arbitrary piece of user data as argument. remark the meaning of ht_enumerate_unhash is not clear. in the current implementation, it will leave the hash table in an inconsistent state. the entries are unlinked from the table, they are not freed, but the entry count (the nentries field of the plhashtable structure) is not decremented. see also pl_hashtableenumerateentries ...
PR_Calloc
elsize to be allocated. elsize the size of an individual element. returns an untyped pointer to the allocated memory, or if the allocation attempt fails, null. call pr_geterror() to retrieve the error returned by the libc function malloc(). description this function allocates memory on the heap for the specified number of objects of the specified size. all bytes in the allocated memory are cleared. ...
PR_GetThreadPrivate
...
PR_NEWZAP
syntax #include <prmem.h> _type * pr_newzap(_struct); parameter _struct the name of a type. returns an pointer to a buffer sized to contain the type _struct, or if the allocation attempt fails, null. the bytes in the buffer are all initialized to 0. call pr_geterror() to retrieve the error returned by the libc function. description this macro allocates an instance of the specified type from the heap and sets the content of that memory to zero. ...
Threads
e data with the new index. pr_setthreadprivate associates private thread data with an index. pr_getthreadprivate retrieves data associated with an index. interrupting and yielding pr_interrupt requests an interrupt of another thread. once the target thread has been notified of the request, the request stays with the thread until the notification either has been delivered exactly once or is cleared. pr_clearinterrupt clears a previous interrupt request. pr_sleep causes a thread to yield to other threads for a specified number of ticks. setting global thread concurrency pr_setconcurrency sets the number of global threads used by nspr to create local threads. getting a thread's scope pr_getthreadscope gets the scoping of the current thread. ...
Certificate functions
nss versions cert_addcerttolisttail mxr 3.2 and later cert_addextension mxr 3.5 and later cert_addocspacceptableresponses mxr 3.6 and later cert_addokdomainname mxr 3.4 and later cert_addrdn mxr 3.2.1 and later cert_asciitoname mxr 3.2 and later cert_cachecrl mxr 3.10 and later cert_clearocspcache mxr 3.11.7 and later cert_certchainfromcert mxr 3.2 and later cert_certlistfromcert mxr 3.2 and later cert_certtimesvalid mxr 3.2 and later cert_changecerttrust mxr 3.2 and later cert_checkcertvalidtimes mxr 3.2 and later cert_checknamespace mxr 3.12 and later cert_checkcertusage m...
NSS FAQ
Mozilla › Projects › NSS › FAQ
a, serbia, sudan, syria, and taleban-controlled areas of afghanistan as of january 2000) or to persons or entities prohibited from receiving u.s. exports (including those (a) on the bureau of industry and security denied parties list or entity list, (b) on the office of foreign assets control list of specially designated nationals and blocked persons, and (c) involved with missile technology or nuclear, chemical or biological weapons). for more information about u.s. export controls on encryption software, see the mozilla crypto faq. ...
JSS Provider Notes
rsapublickey secretkeyfactory secretkey securerandom signature what's not supported the following classes don't work very well: keystore: there are many serious problems mapping the jca keystore interface onto nss's model of pkcs #11 modules. the current implementation is almost useless. since these problems lie deep in the nss design and implementation, there is no clear timeframe for fixing them. meanwhile, the org.mozilla.jss.crypto.cryptostore class can be used for some of this functionality. cipher supported algorithms notes aes des desede (des3 ) rc2 rc4 rsa the following modes and padding schemes are ...
Mozilla-JSS JCA Provider notes
fy() is ignored, because nss does not support specifying an external source of randomness. what's not supported the following classes don't work very well: keystore: there are many serious problems mapping the jca keystore interface onto nss's model of pkcs #11 modules. the current implementation is almost useless. since these problems lie deep in the nss design and implementation, there is no clear timeframe for fixing them. meanwhile, the org.mozilla.jss.crypto.cryptostore class can be used for some of this functionality. ...
NSS 3.16.2 release notes
in pk11pub.h pk11_privdecrypt - decrypts with a private key. the algorithm is specified with a ck_mechanism_type. pk11_pubencrypt - encrypts with a public key. the algorithm is specified with a ck_mechanism_type. new macros in sslerr.h ssl_error_next_protocol_no_callback - an ssl error code that means the next protcol negotiation extension was enabled, but the callback was cleared prior to being needed. ssl_error_next_protocol_no_protocol - an ssl error code that means the server supports no protocols that the client advertises in the alpn extension. notable changes in nss 3.16.2 the btoa command has a new command-line option -w suffix, which causes the output to be wrapped in begin/end lines with the given suffix. use "c" as a shorthand for the suffix certifi...
NSS 3.35 release notes
supports dtls, using the -p option. note that a dtls server is also provided in tstclnt. tls compression is no longer possible with nss. the option can be enabled, but nss will no longer negotiate compression. the signatures of functions ssl_optionset, ssl_optionget, ssl_optionsetdefault and ssl_optiongetdefault have been modified, to take a printn argument rather than prbool. this makes it clearer, that options can have values other than 0 or 1. note this does not affect abi compatibility, because prbool is a typedef for printn. experimental apis and functionality the functionality and the apis listed in this section are experimental. any of these apis may be removed from future nss versions. applications must not rely on these apis to be present. if an application is linked at runti...
NSS 3.54 release notes
nspr 4.26. bug 1642146 - fix undefined reference to `port_zalloc_stub' in seed.c. bug 1642153 - fix infinite recursion building nss. bug 1642638 - fix fuzzing assertion crash. bug 1642871 - enable ssl_sendsessionticket after resumption. bug 1643123 - support ssl_exportearlykeyingmaterial with external psks. bug 1643557 - fix numerous compile warnings in nss. bug 1644774 - ssl gtests to use clearservercache when resetting self-encrypt keys. bug 1645479 - don't use secitem_makeitem in secutil.c. bug 1646520 - stricter enforcement of asn.1 integer encoding. this bugzilla query returns all the bugs fixed in nss 3.54: https://bugzilla.mozilla.org/buglist.cgi?resolution=fixed&classification=components&query_format=advanced&product=nss&target_milestone=3.54 compatibility nss 3.54 shared ...
NSS Sample Code Sample_2_Initialization of NSS
password: ", checkpassword); if (p1) port_free(p1); p1 = getpassword(input, output, "re-enter password: ", checkpassword); if (p0 && p1 && !port_strcmp(p0, p1)) { break; } pr_fprintf(pr_stderr, "passwords do not match. ...
NSS Sample Code sample4
bencryptraw(pubkey, buf2, buf1, modulus_len, null); if (rv != secsuccess) { fprintf(stderr, "encrypt with public key failed (err %d)\n", pr_geterror()); goto cleanup; } pvtkey = pk11_findkeybyanycert(cert, null); if (pvtkey == null) { fprintf(stderr, "couldn't find private key for cert testca (err %d)\n", pr_geterror()); goto cleanup; } /* clear buf1 */ for (i=0;i<modulus_len;i++) { buf1[i]= '\0'; } /* decrypt buf2, result will be in buf1 */ rv = pk11_pubdecryptraw(pvtkey, buf1, &outlen, modulus_len, buf2, modulus_len); if (rv != secsuccess) { fprintf(stderr, "decrypt with private key failed (err %d)\n", pr_geterror()); goto cleanup; } fprintf(stderr, "result of decryp...
NSS Sample Code sample5
ink it is even * ignored */ pk11_importderprivatekeyinfoandreturnkey(slot, &der, null, null, pr_false, pr_true, ku_all, &pvtkey, null); secitem_freeitem(&der, pr_false); if (pvtkey == null) { fprintf(stderr, "couldn't extract private key (err %d)\n", pr_geterror()); goto cleanup; } /* clear buf1 */ for (i=0;i<modulus_len;i++) { buf1[i]= '\0'; } /* decrypt buf2, result will be in buf1 */ rv = pk11_pubdecryptraw(pvtkey, buf1, &outlen, modulus_len, buf2, modulus_len); if (rv != secsuccess) { fprintf(stderr, "decrypt with private key failed (err %d)\n", pr_geterror()); goto cleanup; } fprintf(stderr, "result of decryp...
NSS Sample Code sample6
* * 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 . ...
Initialize NSS database - sample 2
password: ", checkpassword); if (p1) port_free(p1); p1 = getpassword(input, output, "re-enter password: ", checkpassword); if (p0 && p1 && !port_strcmp(p0, p1)) { break; } pr_fprintf(pr_stderr, "passwords do not match. ...
FC_DigestFinal
igestfinal( ck_session_handle hsession, ck_byte_ptr pdigest, ck_ulong_ptr puldigestlen ); parameters hsession [in] session handle. pdigest [out] pointer to the buffer which will receive the digest or null. puldigestlen [in, out] pointer to location containing the maximum buffer size. description fc_digestfinal finishes a multi-part digest operation by returning the complete digest and clearing the operation context. if pdigest is null the length of the digest is returned and fc_digestfinal may be called again with pdigest set to retrieve the digest. a user may call fc_digestfinal without logging into the token (to assume the nss user role). return value examples see also fc_digestinit, nsc_digestfinal ...
FC_FindObjectsFinal
name fc_findobjectsfinal - terminate an object search. syntax ck_rv fc_findobjectsfinal( ck_session_handle hsession, ); parameters hsession [in] session handle. description clears the object search criteria for a session. return value examples see also fc_findobjects, nsc_findobjectsfinal ...
FC_SignFinal
ck_session_handle hsession, ck_byte_ptr psignature, ck_ulong_ptr pussignaturelen ); parameters hsession [in] session handle. psignature [out] pointer to the buffer which will receive the digest or null. pussignaturelen [in, out] pointer 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 ...
NSS tools : modutil
echanism-list to set a module as the default provider for mechanisms, use the -default command with a colon-separated list of mechanisms. the available mechanisms depend on the module; nss supplies almost all common mechanisms. for example: modutil -default "nss internal pkcs #11 module" -dbdir -mechanisms rsa:dsa:rc2 using database directory c:\databases... successfully changed defaults. clearing the default provider has the same format: modutil -undefault "nss internal pkcs #11 module" -dbdir -mechanisms md2:md5 enabling and disabling modules and slots modules, and specific slots on modules, can be selectively enabled or disabled using modutil. both commands have the same format: modutil -enable|-disable modulename [-slot slotname] for example: modutil -enable "nss internal pkc...
NSS tools : ssltab
sha (0x000009) ssl3/rsa/des64cbc/sha (0x000003) ssl3/rsa/rc4-40/md5 } session-id = { } challenge = { 0x0355 0xe6e4 0x9979 0xc7d7 0x2c86 0x7896 0x5db 0xcfe9 } } ] <additional records in same formats> server socket closed. usage tips when ssl restarts a previous session, it makes use of cached information to do a partial handshake. if you wish to capture a full ssl handshake, restart the browser to clear the session id cache. if you run the tool on a machine other than the ssl server to which you are trying to connect, the browser will complain that the host name you are trying to connect to is different from the certificate. if you are using the default badcert callback, you can still connect through a dialog. if you are not using the default badcert callback, the one you supply must allow for t...
NSS tools : ssltap
sha (0x000009) ssl3/rsa/des64cbc/sha (0x000003) ssl3/rsa/rc4-40/md5 } session-id = { } challenge = { 0x0355 0xe6e4 0x9979 0xc7d7 0x2c86 0x7896 0x5db 0xcfe9 } } ] <additional records in same formats> server socket closed. usage tips when ssl restarts a previous session, it makes use of cached information to do a partial handshake. if you wish to capture a full ssl handshake, restart the browser to clear the session id cache. if you run the tool on a machine other than the ssl server to which you are trying to connect, the browser will complain that the host name you are trying to connect to is different from the certificate. if you are using the default badcert callback, you can still connect through a dialog. if you are not using the default badcert callback, the one you supply must allow for t...
NSS reference
dule secmod_unloadusermodule secmod_closeuserdb secmod_openuserdb pk11_findcertfromnickname pk11_findkeybyanycert pk11_getslotname pk11_gettokenname pk11_ishw pk11_ispresent pk11_isreadonly pk11_setpasswordfunc ssl functions based on "ssl functions" in the ssl reference and "ssl functions" and "deprecated ssl functions" in nss public functions. ssl_configserversessionidcache ssl_clearsessioncache s/mime based on the s/mime reference (which only has one written chapter) and "s/mime functions" in nss public functions. pkcs #7 functions based on "archived pkcs #7 functions documentation." pkcs #5 functions password-based encryption sec_pkcs5getiv sec_pkcs5createalgorithmid sec_pkcs5getcryptoalgorithm sec_pkcs5getkeylength sec_pkcs5getpbealgorithm sec_pkcs5isalgorit...
OLD SSL Reference
ssl functions this chapter describes the core ssl functions. ...
sslintro.html
uickly than it can without the connection information. by default, ssl allocates one session cache. this default cache is called the client session id cache, (also known as the client session cache, or simply the client cache). the client cache is used for all sessions where the program handshakes as an ssl client. it is not configurable. you can initialize the client cache with the function ssl_clearsessioncache. if an application will use ssl sockets that handshake as a server, you must specifically create and configure a server cache, using either ssl_configserversessionidcache or ssl_configmpserversidcache. the server cache is used for all sessions where the program handshakes as an ssl server. ssl_clearsessioncache. clears all sessions from the client session cache. optional. ssl_...
ssltyp.html
he shallow copies of that structure and can cause severe problems. pk11slotinfo an opaque structure representing a physical or logical pkcs #11 slot. syntax #include <pk11expt.h> typedef struct pk11slotinfostr pk11slotinfo; secitem a structure that points to other structures. ...
SSL functions
.2 and later ssl_canbypass mxr 3.11.7 and later ssl_cipherpolicyget mxr 3.2 and later ssl_cipherpolicyset mxr 3.2 and later ssl_cipherprefget mxr 3.2 and later ssl_cipherprefgetdefault mxr 3.2 and later ssl_cipherprefset mxr 3.2 and later ssl_cipherprefsetdefault mxr 3.2 and later ssl_clearsessioncache mxr 3.2 and later ssl_configmpserversidcache mxr 3.2 and later ssl_configsecureserver mxr 3.2 and later ssl_configserversessionidcache mxr 3.2 and later ssl_datapending mxr 3.2 and later ssl_forcehandshake mxr 3.2 and later ssl_forcehandshakewithtimeout mxr 3.11.4 and later ssl_get...
NSS Tools modutil
r temporary-directory] deleting a specific pkcs #11 module from a security module database: -delete modulename initializing or changing a token's password: -changepw tokenname [-pwfile old-password-file] [-newpwfile new-password-file] setting the default provider status of various security mechanisms in an existing pkcs #11 module: -default modulename -mechanisms mechanism-list clearing the default provider status of various security mechanisms in an existing pkcs #11 module: -undefault modulename -mechanisms mechanism-list enabling a specific slot or all slots within a module: -enable modulename [-slot slotname] disabling a specific slot or all slots within a module: -disable modulename [-slot slotname] enabling or disabling fips 140-2 compliance within the ne...
NSS Tools ssltap
0x000003) ssl3/rsa/rc4-40/md5 } session-id = { } challenge = { 0x0355 0xe6e4 0x9979 0xc7d7 0x2c86 0x7896 0x5db0xcfe9 }}]<additional records in same formats>server socket closed. usage tips when ssl restarts a previous session, it makes use of cached information to do a partial handshake. if you wish to capture a full ssl handshake, restart the browser to clear the session id cache. if you run the tool on a machine other than the ssl server to which you are trying to connect, the browser will complain that the host name you are trying to connect to is different from the certificate. if you are using the default badcert callback, you can still connect through a dialog. if you are not using the default badcert callback, the one you supply must allow for ...
NSS tools : modutil
Mozilla › Projects › NSS › tools › modutil
to set a module as the default provider for mechanisms, use the -default command with a colon-separated list of mechanisms. the available mechanisms depend on the module; nss supplies almost all common mechanisms. for example: modutil -default "nss internal pkcs #11 module" -dbdir -mechanisms rsa:dsa:rc2 using database directory c:\databases... successfully changed defaults. clearing the default provider has the same format: modutil -undefault "nss internal pkcs #11 module" -dbdir -mechanisms md2:md5 enabling and disabling modules and slots modules, and specific slots on modules, can be selectively enabled or disabled using modutil. both commands have the same format: modutil -enable|-disable modulename [-slot slotname] for example: modutil -enable "ns...
NSS tools : signtool
the -c# option is not used with the -j option, the default compression value is 6. note that versions 1.1 and later of netscape signing tool correctly recognizes the codebase attribute, allows paths to be expressed for the class and src attributes instead of filenames only, processes link tags and parses html correctly, and offers clearer error messages. -l lists the certificates in your database. an asterisk appears to the left of the nickname for any certificate that can be used to sign objects with signtool. --leavearc retains the temporary .arc (archive) directories that the -j option creates. these directories are automatically erased by default. re...
NSS tools : ssltap
Mozilla › Projects › NSS › tools › ssltap
0/md5 } session-id = { } challenge = { 0x0355 0xe6e4 0x9979 0xc7d7 0x2c86 0x7896 0x5db 0xcfe9 } } ] <additional records in same formats> server socket closed. usage tips when ssl restarts a previous session, it makes use of cached information to do a partial handshake. if you wish to capture a full ssl handshake, restart the browser to clear the session id cache. if you run the tool on a machine other than the ssl server to which you are trying to connect, the browser will complain that the host name you are trying to connect to is different from the certificate. if you are using the default badcert callback, you can still connect through a dialog. if you are not using the default badcert callback, the one you supp...
SpiderMonkey Build Documentation
rget=x86_64-pc-mingw32 note: you must have started your mozillabuild shell with the proper -x64.bat script in order for the 64-bit compilers to be in your path. whatever compiler and flags you pass to configure are recorded in the generated makefile, so you don't need to specify them again until you re-run configure. building your application while "how to build your complete application" is clearly out of scope for this document, here are some tips that will help get you on your way: the spidermonkey developers frequently and deliberately change the jsapi abi. you cannot use headers built for one version/configuration of jsapi to create object files which will be linked against another. support for js_threadsafe was recently removed, and threadsafe builds are now enabled by default. ...
GCIntegration - SpiderMonkey Redirect 1
he object that it points to. in the example above, c would be marked when reading it out of a. a very simple way to identify weak pointers is to look for usage of js_isabouttobefinalized(). if a pointer is weak, there's a good chance that js_isabouttobefinalized() is used to null it out if its referent is about to be finalized. however, this search misses some cases like the wrapper cache, where clearwrapper() is called directly from a finalizer. one saving grace is that most weak pointers already have a read barrier on them: xpc_unmarkgray(). besides gray unmarking, this function automatically checks if an incremental gc is running and, if so, marks the given object black. this is how the read barrier for nswrappercache::getwrapper() actually works. moving gc there are two forms of moving ...
Hacking Tips
dware watchpoint 7: *$word // (gdb) cond 7 *$word & $mask // (gdb) cont // // note that this is *not* a watchpoint on a single bit. it is a watchpoint on // the whole word, which will trigger whenever the word changes and the // selected bit is set after the change. // // so if the bit changing is the desired one, this is exactly what you want. // but if a different bit changes (either set or cleared), you may still stop // execution if the $mask bit happened to already be set. gdb does not expose // enough information to restrict the watchpoint to just a single bit. most of the time, you will want js::gc::black (or you can just use 0) for the 2nd param to js::debug::getmarkmask. ...
64-bit Compatibility
- 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-bit platforms. remember to use argsize_p where appropriate - on pointers or natively sized integers (including jsvals). similarly, when adding types to jsbuiltins.h, remember to use _js_ptr for pointer-width values. lir safety it is not immediately clear from reading lir which opcodes should be used for 64-bit safety. if you make a mistake, there's an extremely good chance the sanityfilter in nanojit will catch it while generating code. if this happens you will get an assert that points directly to the ill-typed lir. not all pointer-width values are actually pointers. to avoid equivocating, the rest of this article will use the term "native integ...
Invariants
jsshape and chasing jsshape::parent never forms a cycle and does not contain any duplicate jsscopeproperty::slot values other than -1. (a cycle would be very silly and could cause infloops. the same slot being allocated to more than one property would be a problem for obvious reasons.) all jsshapes in dictionary-mode objects have the in_dictionary flag set. all jsshapes in property trees have it cleared. if an object is inextensible, its dslots will never again change. (we don't bother locking when accessing slots of a sealed object. the locking is going away regardless.) compartments suppose obj = js_getscopechain(cx) is not null. then cx->compartment == obj->compartment(). when a new object is created, it is automatically created in cx->compartment, but its parent and prototype are often...
SpiderMonkey Internals: Thread Safety
ess to jsruntime data structures garbage collection accesses to jsruntime data structures are serialized with a few mutexes. the treatment of gc requires more explanation. making gc thread-safe with js_threadsafe, the api changes slightly. the program must group jsapi calls into "requests": js_setcontextthread(cx); js_beginrequest(cx); /* ... do stuff ... */ js_endrequest(cx); js_clearcontextthread(cx); it isn't a bottleneck; multiple threads are allowed to be in requests on the same jsruntime at once. see js_beginrequest. the most obvious effect of a request is: at any given moment there can either be multiple threads in active requests, or one thread doing gc and all requests suspended. a call to js_gc() will block until the latter becomes possible. in other words, gc waits ...
Introduction to the JavaScript shell
uilt-in functions to make the javascript shell more useful, there are a number of built-in functions provided that you can use either from javascript programs or in interactive mode. note: this list is incomplete and overlaps with shell global objects. see js/src/shell/js.cpp (around shell_functions) for more. build() returns the date and time at which the javascript shell was built. note: clear() with no parameters really clears everything. this includes all these built-in functions. clone(function, [scope]) clones the specified function object. if scope isn't specified, the new object's parent is the same as the original object's. otherwise, the new object is placed in the scope of the object specified by scope. countheap([start[, kind]]) added in spidermonkey 1.8 count the number ...
JS::AutoVectorRooter
void infallibleappend(const t &v) appends an element v to the array. for use when space has already been reserved. void popback() pops an element from the array. t popcopy() pops an element from the array and returns it. bool growby(size_t inc) grows the array by inc. bool resize(size_t newlength) resizes the array to newlength. void clear() clears all elements. bool reserve(size_t newlength) reserves the array with newlength. js::mutablehandle<t> operator[](size_t i) returns to the i-th element as js::mutablehandle&lt;t&gt;. js::handle<t> operator[](size_t i) const returns to the i-th element as js::handle&lt;t&gt;. const t *begin() const returns a pointer to the first element. ...
JSAutoByteString
usivecontext *cx, jsstring *str) call js::lossytwobytecharstonewlatin1charsz, 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 le...
JSDeletePropertyOp
see also mxr id search for jsdeletepropertyop bug 858677 jsclass ...
JSRuntime
each html page; every script in the page could use the same context. objects may be shared among jscontexts within a jsruntime. there's no fixed association between an object and the context in which it is created. sample code to set up and tear down a jsruntime and a jscontext is at jsapi user guide. threads only one thread may use a jscontext or jsruntime. earlier versions allowed using js_clearcontextthread and other functions to move a jscontext from one thread to another. this feature has since been removed. see also js_newruntime js_destroyruntime js_newcontext js_destroycontext ...
JS_DeleteElement
eleteelement 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_DeleteElement2
es from objects as long as they are not also permanent. for javascript 1.2 and earlier, if deletion fails because the property is permanent, js_deleteelement2 reports the error and returns false. for javascript 1.3, the attempt is silently ignored. in both these cases, *succeeded will receive the stored value of the property that was not deleted. to remove all properties from an object, call js_clearscope. see also mxr id search for js_deleteelement2 bug 1113369 -- added result parameter ...
JS_DeleteProperty
tions return true on success, regardless of whether a property was actually deleted, and false on error or exception. (in javascript 1.2 and earlier, attempting to delete a permanent property caused an error. there is no longer any way to get this behavior.) internally, property deletion is implemented by the jsobjectops.deleteproperty callback. to remove all properties from an object, call js_clearscope. see also mxr id search for js_deleteproperty mxr id search for js_deletepropertybyid js_deleteproperty2 js_deletepropertybyid2 bug 461163 bug 1113369 -- added result parameter and js_deleteucproperty ...
JS_DeleteProperty2
regardless of whether a property was actually deleted. on error or exception, the return value is false, and the value left in *succeeded is unspecified. jsobjectops.deleteproperty implements this behavior. (in javascript 1.2 and earlier, attempting to delete a permanent property caused an error. there is no longer any way to get this behavior.) to remove all properties from an object, call js_clearscope. see also mxr id search for js_deleteproperty2 mxr id search for js_deleteucproperty2 mxr id search for js_deletepropertybyid2 bug 461163 bug 1113369 -- renamed to js_deleteproperty ...
JS_ReportPendingException
x); name type description cx jscontext * the context in which the exception was thrown. requires request. in a js_threadsafe build, the caller must be in a request on this jscontext. description if an exception is pending in the context cx, js_reportpendingexception converts the exception to a string and reports it to the current error reporter. on success, it clears the exception as though by calling js_clearpendingexception and returns true. if no exception is pending, or if a second error occurs while trying to report the first one, it returns false. this function can be used to catch exceptions thrown from scripts and send them to the error reporter to be logged or ignored. note that certain jsapi functions automatically do this for uncaught exceptions; ...
JS_RestoreExceptionState
see also mxr id search for js_restorestateexception jsexceptionstate js_saveexceptionstate js_dropexceptionstate ...
JS_SaveExceptionState
cified context. syntax jsexceptionstate * js_saveexceptionstate(jscontext *cx); name type description cx jscontext * pointer to a js context from which to derive runtime information. requires request. in a js_threadsafe build, the caller must be in a request on this jscontext. description saves the current exception state (that is, any pending exception, or a cleared exception state) associated with the specified context cx, and returns a jsexceptionstate object holding this state. that object may then be used to restore again the context using js_restoreexceptionstate, or discarded using js_dropexceptionstate. either of those two functions frees any memory used by the jsexceptionstate. the jsexceptionstate created by this function automatically roots any p...
JS_SetAllNonReservedSlotsToUndefined
this article covers features introduced in spidermonkey 24 assign undefined to all of the object's non-reserved slots. note: this is done for all slots, regardless of the associated property descriptor. syntax void js_setallnonreservedslotstoundefined(jscontext *cx, jsobject *objarg); name type description cx jscontext * the context in which to clear the object. requires request. in a js_threadsafe build, the caller must be in a request on this jscontext. obj jsobject * object from which to delete all properties. description js_setallnonreservedslotstoundefined assignes undefined to all of obj's own properties, except the special __proto__ and __parent__ properties, in a single operation. properties belonging to objects o...
JS_SetOperationCallback
te that mozilla does not do this, by design); to enforce application limits on the amount of time a script may run. (in this case, the callback may terminate the script by returning js_false.) js_getoperationcallback returns the currently installed operation callback, or null if none is currently installed. js_triggeroperationcallback triggers a callback set using js_setoperationcallback. js_clearoperationcallback clears the current operation callback. obsolete since javascript 1.9.1 js_setoperationcallbackfunction sets the operation callback without changing the operation limit. obsolete since javascript 1.9.1 js_getoperationlimit returns the current operation limit, or js_max_operation_limit if no operation callback is currently installed. obsolete since javascript 1.9.1 js_setoperati...
JS_SetPendingException
o throw as an exception. ...
JS_SetRegExpInput
ne. ...
JS_SetThreadStackLimit
eadstacklimit sets the maximum (if stack grows upward) or minimum (downward) legal stack byte address in limitaddr for the thread or process stack used by cx. to disable stack size checking, pass 0 for limitaddr. in a js_threadsafe build, after passing a jscontext from one thread to another, call js_setthreadstacklimit(cx, 0) after calling js_setcontextthread. (see also js_setcontextthread and js_clearcontextthread.) see also mxr id search for js_setthreadstacklimit js_setnativestackquota bug 723021 ...
JS_THREADSAFE
d to share contexts across threads. for example: many worker threads need to share a "pool" of reusable contexts, to avoid the performance cost of constantly creating and destroying contexts. (this is analogous to a database connection pool.) the application has a jscontext that it needs to use each time some event happens. but the event could happen on any thread. for such cases, use js_clearcontextthread and js_setcontextthread to transfer the context safely from one thread to another. further info note: spidermonkey internals: thread safety is mostly obsolete. ...
SpiderMonkey 17
and js_constructobjectwitharguments (preferably use js_new instead, or use this reimplementation as a short-term fix) js_newcompartmentandglobalobject (use js_newglobalobject instead.) jspd_argument jsval_is_object() (use !jsval_is_primitive(v) to detect objects and jsval_is_null(v) to detect null). js_isscriptframe jsclass_new_resolve_gets_start flag js_newnumbervalue js_finalizestub js_clearnewbornroots jsclass_mark_is_trace flag js_setscriptstackquota api changes break out and discuss all api changes here... jsclass prototype has changed a number of optional members have been removed from the jsclass prototype. jsclass callback changes many of the jsclass callbacks such as jsresolveop, jsenumerateop and jspropertyop, have a type change on their arguments to jshandleobject, jshand...
SpiderMonkey 38
g 952650) jsval_is_int (bug 952650) jsval_is_null (bug 952650) jsval_is_number (bug 952650) jsval_is_primitive (bug 952650) jsval_is_string (bug 952650) jsval_is_void (bug 952650) jsval_to_boolean (bug 952650) jsval_to_double (bug 952650) jsval_to_gcthing (bug 952650) jsval_to_int (bug 952650) jsval_to_object (bug 952650) jsval_to_private (bug 952650) jsval_to_string (bug 952650) js_clearnonglobalobject (bug 1043281) js_clonefunctionobject (bug 1089026) js_compilefunction (bug 1089026) js_compileucfunction (bug 1089026) js_convertarguments (bug 1125784) js_convertargumentsva (bug 1125784) js_convertstub (bug 1103152) js_defineownproperty (bug 1017323) js_deletepropertystub (bug 1103152) js_doubletoint32 (bug 1112774) js_doubletouint32 (bug 1112774) js_enumeratestub (bug...
Redis Tips
even if i have a private redis db for this app, this is descriptively useful and adds a measure of safety. if i ever have more values to store per email than just the password, i could use a hash, with a key like ptu:identity:<email>. in the case where you want to do something akin to a join, like, say, associate an email and a remote url to store a browserid asser...
Handling Mozilla Security Bugs
rpose). mozilla distributors who wish to inform their users of the existence of a vulnerability may repost any information from the known vulnerabilities page to their own websites, mailing lists, release notes, etc., but should not disclose any additional information about the bug. the original reporter of a security bug may decide when that bug report will be made public. disclosure is done by clearing the bug's "security-sensitive" flag, after which the bug will revert to being an ordinary bug. we believe that investing this power in the bug reporter simply acknowledges reality, as nothing prevents the person reporting a security bug from publicizing information about the bug by posting it to channels outside the context of the mozilla project. by not doing so, and by instead choosing to re...
Using the Places history service
unvisited. nsiglobalhistory3.getgeckoflags: retrieves information previously set using setgeckoflags. it is not yet implemented in the places history system. nsibrowserhistory.lastpagevisited: contains the uri of the last page visited. this is used when the preference is set that causes the last page in new windows. nsibrowserhistory.count: the number of pages in history. this is used by the "clear history" button to determine if there are any pages in history. because actually counting all the pages in history is expensive,navhistory will always return the value 0 or 1. 0 is returned when there is no history, 1 is returned when there are one or more pages in history.deprecated, use hashistoryentries instead. nsinavhistoryservice.hashistoryentries: exactly the same as nsibrowserhistory.cou...
Avoiding leaks in JavaScript XPCOM components
etermine which objects are still needed by starting from a set of roots and finding all objects reachable from those objects and (2) returning all remaining objects to the heap. the roots include things like global variables and variables on the current call stack. mozilla's javascript engine uses one of the most common garbage collection algorithms, mark and sweep, in which the garbage collector clears the mark bit on each object, sets the mark bits on all roots and all objects reachable from them, and then finalizes all objects not marked and returns the memory they used to the heap. garbage collection (at least when the term is not used to refer to lesser algorithms like reference counting) is pretty good at freeing memory that should be freed. however, in a fully garbage-collected system t...
An Overview of XPCOM
d to do. one rule might specify that dosomethinguseful may only be called after a call to init(). the dosomethinguseful method may do some kind of checking to ensure that the condition - that init has been called - has been satisfied. in addition to writing well-commented code that tells the client developer the rules about init(), the developer can take a couple steps to make this contract even clearer. first, the construction of an object can be encapsulated, and a virtual class provided that defines the dosomethinguseful method. in this way, construction and initialization can be completely hidden from clients of the class. in this "semi-encapsulated" situation, the only part of the class that is exposed is a well-defined list of callable methods (i.e., the interface). once the class is enc...
Finishing the Component
r service manager to access the interface you want, and the xpcom object(s) that implement that interface will do your bidding. with this huge amount of flexibility, however, you lose compatibility. if you use "stuff" that isn't frozen, that stuff is subject to change in future versions of gecko. if you want to be protected against changes in gecko, you must only use interfaces and apis that are clearly marked as frozen. the marking is made in the comments above the interface declaration. for example, take a look at the nsiservicemanager: /** * the nsiservicemanager manager interface provides a means to obtain * global services in an application. the service manager depends * on the repository to find and instantiate factories to obtain * services. * * users of the service manager must ...
Preface
the sdk, building, and getting programmatic access to gecko components are provided in the appendix to this book, setting up the gecko sdk. conventions the formatting conventions listed below are used to designate specific types of information in the book and make things easier to scan. the goal is to use as few formats as possible, but to distinguish the various different types of information clearly. format description bold component names appear in bold in the text monospace code listings, interface names and members of interfaces (e.g., createinstance()) appear in monospaced font. lines of code are placed in separate boxes. additionally, filenames and directories appear in monospaced font. italic variables appear in italic. important terms...
Starting WebLock
en you want to pass primitive data types like numbers, strings, characters, void *, and others, the solution is to use one of the nsisupportsprimitive interfaces. these interfaces wrap primitive data types and derive from nsisupports. this allows types like the strings that represent urls in the weblock component to be passed though methods that take an nsisupports interface pointer. ...
Using XPCOM Components
this example shows is the availability of the queryinterface method on all objects that are reflected into javascript from xpcom. as in c++, you can use this method to ask for other interfaces that are available on the given object. services versus regular instances whether to have clients use your component as an instance or a service is a design question, really, and something you should be clear about in the documentation for your component. actually, the getservice() method in the example here calls through to the createinstance() method that is also available from the component object and caches the result, making it a singleton rather than a normal instance. the singleton design pattern that is used to create services is described in xpcom services. remember, queryinterface allows ...
Using XPCOM Utilities to Make Things Easier
isupports declares methods of nsisupports including mrefcnt ns_init_isupports initializes mrefcnt to zero. must be called in class's constructor ns_get_iid returns the iid given the name of an interface. interface must be generated by xpidl using the macros described here, the code for the weblock component has gone from around 340 lines of code to just under 40. clearly from a code maintenance point of view, this kind of reduction is outstanding. the entire source file with these macros included appears in weblock2.cpp. weblock2.cpp the listing below shows the generic module code from weblock1.cpp using the macros described in this chapter: weblock2.cpp #include "nsigenericfactory.h" #include "nsisupportsutils.h" #define sample_cid \ { 0x777f7150, 0x4a2b,...
Mozilla internal string guide
t is often necessary to insert literal string values when an nsastring or nsacstring is required. two user-defined literals are provided that implicitly convert to const nsstring& resp. const nscstring&: ""_ns for 8-bit literals, converting implicitly to const nscstring& u""_ns for 16-bit literals, converting implicitly to const nsstring& the benefits of the user-defined literals may seem unclear, given that nsdependentcstring will also wrap a string value in an nscstring. the advantage of the user-defined literals is that the length of these strings is calculated at compile time, so the string does not need to be scanned at runtime to determine its length. nowadays, all supported platforms have 16-bit literals using u""_ns, so we longer need to rely on macros for portability. // call i...
How to build a binary XPCOM component using Visual Studio
pecialthing_contractid, cspecialthingconstructor, } }; ns_impl_nsgetmodule("specialthingsmodule", components) assuming you have the right sdk and setup the include and lib folders correctly, the project should build your xpcom component. test component in a xulrunner application in order to test your component in a xulrunner application, you need to “install” the component, “clear” the component registry, and use the component from javascript. install component: copy your xpt and dll files to the {app}/components folder. you should not put your component in the xulrunner/components folder. clear registry: increment the buildid in your {app}/application.ini. use in javascript: function doxpcom() { try { const cid = "@starkravingfinkle.org/specialthing;1"; v...
Components.utils.unload
ude as part of your extension. syntax components.utils.unload( url ); parameters url the "resource://" url of the script to unload. this must be the same url that was used to load the script. example you can unload a module called mymodule.jsm using the following line of code: components.utils.unload("resource://myaddon/modules/mymodule.jsm"); note: currently components.utils.unload clears the global object of an unloaded module. this may cause modules to misbehave after unloading even if you have a reference to them. see bug 769253 see also bug 481603 the documentation in xpccomponents.idl the tests in js/xpconnect/tests/unit/ ...
XPCShell Reference
for (prop in arguments) { print(prop + "=" + arguments[prop]); } entering the following at the command line should produce the following output: $ xpcshell test.js this is a test 0=this 1=is 2=a 3=test xpcshell extensions once you execute xpcshell without a script you'll be at the js> command line. the following are some useful functions that can be invoked from the command line: clear(object) clear() removes all properties from an object. for example, if you created anobject with a property named value and then called clear(anobject), the property value would no longer exist. gc(heapdumpfilename) gc() will invoke garbage collection. it takes an optional argument that can be used to dump the heap to. if specified, it should equate to a valid filename. load(scriptfilen...
imgICache
(relevantdocument); // alternatively, tools.getimgcacheforchannel(relevantchannel) if there is no relevant document or channel, null may be passed, but this will cause any image cache requests to use the permanent storage cache (ie. any images from windows in private browsing mode will not be present in the cache returned from a call with a null parameter). method overview void clearcache(in boolean chrome); nsiproperties findentryproperties(in nsiuri uri); void removeentry(in nsiuri uri); methods clearcache() evict images from the cache. void clearcache( in boolean chrome ); parameters chrome if true, evict only chrome images. if false, evict everything except chrome images. findentryproperties() find properties us...
mozIAsyncFavicons
ptional] in prtime aexpiration); parameters afaviconuri uri of the favicon whose data is being set. adata binary contents of the favicon to save. adatalen length of binary data amimetype mime type of the data to store. this is important so that we know what to report when the favicon is used. you should always set this param unless you are clearing an icon. aexpiration optional time in microseconds since the epoch when this favicon expires. until this time, we won't try to load it again. replacefavicondatafromdataurl() same as replacefavicondata() but the data is provided by a string containing a data url. favicon data for favicon uris that are not associated with a page uri via setandfetchfaviconforpage will be stored in ...
mozIPersonalDictionary
language of the word. note that this parameter is currently unused. check() checks a unicode string. boolean check( in wstring word, in wstring lang ); parameters word the word to check. lang the language of the word. note that this parameter is currently ignored. return value true if the word is in either the dictionary or the ignore list, false if it is not in either list. endsession() clears the ignore list. void endsession(); parameters none. getcorrection() gets a list of previous corrections for the word. void getcorrection( in wstring word, [array, size_is(count)] out wstring words, out pruint32 count ); parameters word the word to get the list of corrections for. words the list of corrections. count the number of corrections in the list. ignoreword() adds a word to th...
nsIAsyncInputStream
utstreamready() event will be dispatched immediately. otherwise, the event will be dispatched when the stream becomes readable or closed. void asyncwait( in nsiinputstreamcallback acallback, in unsigned long aflags, in unsigned long arequestedcount, in nsieventtarget aeventtarget ); parameters acallback this object is notified when the stream becomes ready. this parameter may be null to clear an existing callback. aflags this parameter specifies optional flags passed in to configure the behavior of this method. pass zero to specify no flags. arequestedcount wait until at least this many bytes can be read. this is only a suggestion to the underlying stream; it may be ignored. the caller may pass zero to indicate no preference. aeventtarget specify null to receive notification on any th...
nsIAsyncOutputStream
tstreamready() event will be dispatched immediately. otherwise, the event will be dispatched when the stream becomes writable or closed. void asyncwait( in nsioutputstreamcallback acallback, in unsigned long aflags, in unsigned long arequestedcount, in nsieventtarget aeventtarget ); parameters acallback this object is notified when the stream becomes ready. this parameter may be null to clear an existing callback. aflags this parameter specifies optional flags passed in to configure the behavior of this method. pass zero to specify no flags. arequestedcount wait until at least this many bytes can be written. this is only a suggestion to the underlying stream; it may be ignored. the caller may pass zero to indicate no preference. aeventtarget specify null to receive notification on any...
nsIAuthInformation
log. a bitwise or of the constants. it is possible that neither #auth_host nor #auth_proxy are set. auth prompts should ignore flags they do not understand; especially, they should not throw an exception because of an unsupported flag. read only. password astring the initial value should be used to prefill the dialog or be shown in some other way to the user. the password should not be shown in clear. on return, this parameter should contain the password entered by the user. realm astring the server-supplied realm of the authentication as defined in rfc 2617. can be the empty string if the protocol does not support realms. otherwise, this is a human-readable string like "secret files". read only. username astring the initial value should be used to prefill the dialog or be shown in some o...
nsIBrowserHistory
that is to be marked as currently open. removeallpages() this method removes all the pages from the global history. void removeallpages(); parameters none. remarks visits are removed synchronously, but pages are expired asynchronously, off the main thread. note: removals are handled in a batch. single removals are not subject to individual notification; instead, nsinavhistoryobserver.onclearhistory() is called on the history observer. removepage() this method removes all visits for a page from the history. the page itself is only deleted when it is not bookmarked and when it is not a place: uri. this method is called by the ui when the user deletes a history entry. note: if removing fewer than 10 pages, calling this repeatedly is preferable over calling removepages(), since that's...
nsIClipboard
te operations are using. constant value description kselectionclipboard 0 clipboard for selection. kglobalclipboard 1 clipboard for global use. kfindclipboard 2 clipboard for find strings. methods emptyclipboard() this method empties the clipboard and notifies the clipboard owner. it empties the "logical" clipboard. it does not clear the native clipboard. void emptyclipboard( in long awhichclipboard ); parameters awhichclipboard specifies the clipboard to which this operation applies. forcedatatoclipboard() obsolete since gecko 1.8 (firefox 1.5 / thunderbird 1.5 / seamonkey 1.0) some platforms support deferred notification for putting data on the clipboard this method forces the data onto...
nsIClipboardCommands
ne. copyselection() copy the current selection onto the clipboard. void copyselection(); parameters none. cutselection() cut the current selection onto the clipboard. void cutselection(); parameters none. paste() paste the contents of the clipboard into the current selection. void paste(); parameters none. selectall() select the entire contents. void selectall(); parameters none. selectnone() clear the current selection (if any). insertion point ends up at beginning of current selection. void selectnone(); parameters none. see also nsiclipboard ...
nsIConsoleService
to notify when an error is logged. note: to guard against stack overflows from listeners which could log messages (this could be done inadvertently through listeners implemented in javascript), we do not call any listeners when another error is already being logged. void registerlistener( in nsiconsolelistener listener ); parameters listener the nsiconsolelistener to add. reset() to clear the message buffer (for example, for privacy reasons): void reset(); 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 n...
nsIContentPrefService
aname the name of the preference whose existence is to be determined. return value true if the preference exists; otherwise false. exceptions thrown ns_error_illegal_value if agroup is not a string, nsiuri, or null. or if aname is null or an empty string removegroupedprefs() remove all grouped prefs. useful for removing references to the sites the user has visited when the user clears their private data. void removegroupedprefs(); removeobserver() removes an observer that's presently monitoring a preference for changes. void removeobserver( in astring aname, in nsicontentprefobserver aobserver ); parameters aname the name of the preference to stop observing. you may specify null to remove a generic observer that is monitoring all preference changes. aobserv...
nsICookieService
deleted cookie. added a cookie was added. the subject is the added cookie. changed a cookie was changed. the subject is the changed cookie. batch-deleted a set of cookies were deleted as part of a purge operation. this typically happens because they have either expired or because the cookie list has grown too large. the subject is an nsiarray of deleted cookies. cleared the entire cookie list was cleared. the subject is null. reload the entire cookie list was changed, and the observer should reload the list of cookies. the subject is null. private-cookie-changed since firefox 20 (see bugzilla #837091) same as cookie-changed, except used in lieu of cookie-changed for private windows. see cookie-changed. cookie...
nsIDNSService
lag constants. return value dns record corresponding to the given host name. exceptions thrown ns_error_unknown_host if host could not be resolved. shutdown() obsolete since gecko 1.8 (firefox 1.5 / thunderbird 1.5 / seamonkey 1.0) called to shutdown the dns service. any pending asynchronous requests will be canceled, and the local cache of dns records will be cleared. note: the operating system may still have its own cache of dns records, which would be unaffected by this method. void shutdown(); parameters none. example let dnsservice = components.classes["@mozilla.org/network/dns-service;1"] .createinstance(components.interfaces.nsidnsservice); let thread = components.classes["@mozilla.org/thread-manager;1"] .getservice(com...
nsIFrameLoader
astring atype, in boolean capture ); parameters atype the event type for which to enable forwarding. capture whether or not to capture these events. activateremoteframe() activates the remote frame. void activateremoteframe(); parameters none. exceptions thrown throws an exception with non-remote frames. destroy() destroys the frame loader and everything inside it. this will clear the weak owner content reference. void destroy(); parameters none. loadframe() starts loading the frame. this method figures out what to load from the owner content in the frame loader. void loadframe(); parameters none. loaduri() loads the specified uri in this frame. behaves identically to loadframe(), except that this method lets you specify the uri to load. void loaduri( in nsi...
nsIJumpListBuilder
are generated automatically by windows. applications that use recent or frequent lists should keep document use tracking up to date by calling the shaddtorecentdocs shell api. jumplist_category_customlist 3 custom lists can be made up of tasks, links, and separators. the title of of the list is passed through the optional string parameter of addbuildlist. methods abortlistbuild() aborts and clears the current jump list build. void abortlistbuild(); parameters none. addlisttobuild() adds a list and if required, a set of items for the list. boolean addlisttobuild( in short acattype, in nsiarray items, optional in astring catname optional ); parameters acattype the type of list to add. items optional an array of nsijumplistitem items to add to the list. catname optional for custom l...
nsILivemarkService
dentifies a folder that isn't a livemark container; also if the feeduri parameter isn't a valid nsiuri object. setsiteuri() this method sets the uri of the website associated with a livemark container. void setsiteuri( in long long container, in nsiuri siteuri ); parameters container the folder id of a livemark container. siteuri nsiuri object representing the site uri, or null to clear the site uri for this livemark container. exceptions thrown ns_error_invalid_arg if the folder id isn't known or identifies a folder that isn't a livemark container; also if the siteuri argument isn't a valid nsiuri object (or null) start() this method starts the livemark refresh timer. being able to manually control this allows activity such as bookmarks import to occur without kicking ...
nsILoginManagerStorage
ogininfo oldlogin, in nsisupports newlogindata ); parameters oldlogin the login to be modified. newlogindata the login information to replace the oldlogin with. this may be specified as either an nsilogininfo or an nsipropertybag2 object. removealllogins() implement this method to remove all logins from the login store. this is called by the browser sanitization feature when the user asks to clear all stored passwords. the user interface allows this to be done without getting each login first (which might require knowing the master password). no password should be required in order to remove all logins. void removealllogins(); parameters none. removelogin() implement this method to remove the specified login from the login store. gecko 1.9.1 note the values of any nsiloginmetainfo pr...
nsIMsgFilter
g headersize, out boolean result ) logrulehit() void nsimsgfilter::logrulehit ( in nsimsgruleaction afilteraction, in nsimsgdbhdr aheader ) createaction() nsimsgruleaction nsimsgfilter::createaction ( ) getactionat() nsimsgruleaction nsimsgfilter::getactionat (in long aindex) appendaction() void nsimsgfilter::appendaction (in nsimsgruleaction action ) clearactionlist() void nsimsgfilter::clearactionlist() getsortedactionlist() void nsimsgfilter::getsortedactionlist (in nsisupportsarray actionlist) ...
nsIMsgFilterList
stream ) writewstrattr() void nsimsgfilterlist::writewstrattr ( in nsmsgfilterfileattribvalue attrib, in string value, in nsioutputstream stream ) matchorchangefiltertarget() boolean nsimsgfilterlist::matchorchangefiltertarget ( in acstring olduri, in acstring newuri, in boolean caseinsensitive ) clearlog() void nsimsgfilterlist::clearlog () ensurelogfile() void nsimsgfilterlist::ensurelogfile () flushlogifnecessary () void nsimsgfilterlist::flushlogifnecessary () const const nsmsgfilterfileattribvalue nsimsgfilterlist::attribnone = 0 const nsmsgfilterfileattribvalue nsimsgfilterlist::attribversion = 1 const nsmsgfilterfileattribvalue nsimsgfilterlist::attriblogging = 2 const ns...
nsINavHistoryService
atchcallback acallback, in nsisupports aclosure); void importhistory(in nsifile file); astring getcharsetforuri(in nsiuri auri); astring setcharsetforuri(in nsiuri auri, in astring acharset); attributes attribute type description hashistoryentries boolean true if there is any history. this can be used in ui to determine whether the "clear history" button should be enabled or not. this is much better than using browserhistory.count since that can be very slow if there is a lot of history (it must enumerate each item). this is pretty fast. historydisabled boolean true if history is disabled. currently, history is disabled if the browser.history_expire_days pref is "0". constants transition type constants ...
nsIPrincipal
te principal. this may change in a future release; note that nsiprincipal is unfrozen, not slated to be frozen. xxxbz except see bug 147145! note: for the future: perhaps we should consider a certificate principal for a given uri subsuming a codebase principal for the same uri? not sure what the immediate benefit would be, but i think the setup could make some code (e.g. maybedowngradetocodebase) clearer. boolean subsumes( in nsiprincipal other ); parameters other missing description return value true if this principal subsumes the specified principal; otherwise false. ...
nsITreeView
he cell to. setcellvalue() setcellvalue is called when the value of the cell has been set by the user. this method is only called for columns of type other than text. void setcellvalue( in long row, in nsitreecolumn col, in astring value ); parameters row the row of the cell. col the column of the cell. value the value to change the cell to. settree() called when setting or clearing the view on the tree to link the view to or disconnect the front end box object. void settree( in nsitreeboxobject tree ); parameters tree the nsitreeboxobject to attach this view to, or null if the view is being removed from the tree. toggleopenstate() called on the view when an item is opened or closed, e.g., by clicking the twisty, keyboard access, et cetera. note: as of this w...
nsIURI
rning a new nsiuri object. note: for some protocols, this is more than just an optimization. for example, under mac os x, the spec of a file uri doesn't necessarily uniquely identify a file, since two volumes can have the same name. nsiuri clone(); parameters none. return value an nsiuri object that represents the same uri as the current nsiuri. cloneignoringref() clones the current uri, clearing the 'ref' attribute in the clone. nsiuri cloneignoringref(); parameters none. return value an nsiuri object that represents the same uri as the current nsiuri without the 'ref' attribute. equals() compares the current uri with another uri. note: this is more than a string comparison, as two different uri strings can represent the same location. for example, comparing "http://foo.com:8...
nsIWebContentHandlerRegistrar
e registerprotocolhandler will get the contentwindow from it nsiwchr.registerprotocolhandler("mailto", "http://mail.live.com/secure/start?action=compose&to=%s", "outlook.com live mail", htmlcontentwindow); if (!allowregisterfromdifferenthost) { //it this variable is false, than we had set the pref to true obviously. so lets restore it back to false, which is the default value services.prefs.clearuserpref('gecko.handlerservice.allowregisterfromdifferenthost'); } register a webmail service as mailto handler without contentwindow under construction. to take from: http://mxr.mozilla.org/mozilla-release/source/browser/components/feeds/src/webcontentconverter.js#372 and http://stackoverflow.com/questions/24900655/use-registerprotocolhandler-without-contentwindow place holder see also n...
nsIWindowWatcher
to an nsidomwindow. atopic - a wstring, either "domwindowopened" or "domwindowclosed". adata - not used. setwindowcreator() set the window creator callback. it must be filled in by the app. openwindow() will use it to create new windows. void setwindowcreator( in nsiwindowcreator creator ); parameters creator the nsiwindowcreator callback. if this is null the callback will be cleared and window creation capabilities lost. unregisternotification() 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 removes an nsiobserver from the list of objects to be notified. void unregisternotification( in nsiobserver aobserver ); parameters aobserver the nsiobserver to be removed...
Weak reference
u call it through, and no matter when you call it. this is impossible in our situation, since we explicitly rely on the the fact that part of the `aggregate' can be destroyed. subsequent attempts to reach that part must return nsnull. sometimes our queryinterface through the weak pointer would return a pointer to the `real' interface, and sometimes it would return nsnull. we just broke com. it's clear, therefore, that the weak reference can't be aggregated to the target object. hence, we can't use queryinterface to move between them. i know this sounds more convenient, but the global routine ns_getweakreference makes it easy to go from the target object to the weak reference; and nsiweakreference::queryreferent gives you the same functionality as queryinterface for getting back. additionally, ...
XPIDL
larations, which means certain compilers (e.g. clang and gcc) will reports errors if these results are not used. source and binary compatibility some consumers of idl interfaces create binary plugins that expect the interfaces to be stored in a specific way in memory. in other words, some changes made to idl interfaces require the author to modify the unique identifier (iid) in order to make it clear to plugins that utilize these interfaces that they have changed, and thus their plugin must be recompiled. common changes to an interface, such as changes to a method signature, number of arguments, and number or type of attributes, automatically require an iid change. in addition, some changes to interface attributes require that an iid be changed, as well. when a change to an interface made by...
Xray vision
ffect the c++ representation. the dual representation enables an elegant implementation of xrays: the xray just directly accesses the c++ representation of the original object, and doesn't go to the content's javascript reflection at all. instead of filtering out modifications made by content, the xray short-circuits the content completely. this also makes the semantics of xrays for dom objects clear: they are the same as the dom specification, since that is defined using the webidl, and the webidl also defines the c++ representation. xrays for javascript objects until recently, built-in javascript objects that are not part of the dom, such as date, error, and object, did not get xray vision when accessed by more-privileged code. most of the time this is not a problem: the main concern xra...
Address book sync client design
, // mark the entry deleted, etc. // // sync approach - server handles all conflict resolution: // // step 2: // using the sync mapping table and the local records database, generate the change // list to send to the server. mark any modified or new record with the ret (retry) // flag. // // step 3: // get the response back from the server. since the communication was successful, // clear the ret (retry) flag on all records. then apply the server changes back // to the local database (updating the crc's in the process). save the changes to // the local database, clear the sync mapping table flags and save the new sync // mapping table. // public interfaces there is a very simple interface to the address book sync component. this interface is defined in...
Folders and message lists
essage(msghdr): selects a single message, as specified by msghdr (an nsimsgdbhdr) and scrolls to its position in the message list. gfolderdisplay.selectmessages(arrayofmsghdrs): selects all the messages in the array arrayofmsghdrs. like selectmessage, this function will attempt to scroll the view so the entire selection is visible (which may not be possible for large selections). gfolderdisplay.clearselection(): clears the list of selected messages. listing messages in a folder if you have a message folder, and would like to list all the messages in that folder, you can use the .messages attribute, which returns an nsisimpleenumerator. it's used like this: // import the fixiterator() function. components.utils.import("resource:///modules/iteratorutils.jsm"); for (let msghdr in fixiterato...
Accessibility Inspector - Firefox Developer Tools
the accessibility inspector panel displays only the items that have that type of issue. in the right side of the panel, the checks subpanel lists the specific issue with the selected node. for each type of issue, there is a learn more link to further information on mdn web docs about the issue. the menu items act as toggles. select the item to view that type of issue; select the item again to clear the display of issues of that type. issues with a particular item are always displayed in the checks subpanel as you browse the tree. the check for issues menuitems are a quick way to view all and only those items that have issues. simulate the accessibility inspector offers (as of firefox 70), a simulator that lets you see what a web page would look like to users with various forms of color v...
Introduction to DOM Inspector - Firefox Developer Tools
—all without actually changing the dom as it is defined in the file on disk. loving the inspector the dom inspector can take some figuring out, but once you get used to it, you may find that these structured views of web pages and interfaces were exactly the aspects of your own application development that were missing. the dom inspector not only presents all this information about pages in a clear and structured way, it gives you way to find and update those structures, and it's simple to access via shortcuts and menus already available in the mozilla browser. used in concert with mozilla tools like venkman, the javascript debugger, the dom inspector can give you a complete view of any web page or dom-based application interface. ...
Browser Toolbox - Firefox Developer Tools
...
Tutorial: Show Allocations Per Call Path - Firefox Developer Tools
de. (the line number for the onclick handler is 1, indicating that the allocating call is located on line one of the handler text itself. ...
Deprecated tools - Firefox Developer Tools
lti-line javascript code in the web console editor mode, making it similar to the scratchpad. the editor mode can be triggered clicking on the icon on the right of the console input, or with ctrl + b (cmd + b on macos) when in editor mode, the enter key adds a new line in the input, and you can evaluate the expression using ctrl + enter (cmd + enter on macos). when evaluating, the input isn't cleared, which makes it possible to quickly iterrate over a snippet of code. the results are displayed in the console output, to the right of the input, providing immediate feedback. unlike in scratchpad, errors are properly displayed in the output with an expandable stacktrace, making it easier to debug the code you're currently writing. starting firefox 72, you can import a javascript file content ...
Basic operations - Firefox Developer Tools
efault 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. 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. to load a snapshot from an existing .fxsnapshot file, click the import butt...
Examine and edit CSS - Firefox Developer Tools
markup view next to all nodes to which the pseudo-class has been applied. in addition, the information that appears on the page itself show you what pseudo-class you are examining. for example: viewing and changing classes on an element with an element selected in the html pane, you can click the .cls button in the rules pane toolbar, to display the classes defined on that element. you can clear the checkbox for a particular class name, to see how the element would appear without that class applied to it. you can add a class to the element by typing a name in the add new class field below the rules toolbar. autocompletions based on existing classes are suggested as you type. link to css file at the top right of each rule, the source filename and line number is displayed as a link: cl...
Animation inspector example: CSS transitions - Firefox Developer Tools
width: 0; transition: opacity 500ms 150ms, width 500ms 150ms; } .icon#selected { filter: grayscale(0%); transform: scale(1.5); } .icon#selected+span { opacity: 1; width: 300px; } javascript content function toggleselection(e) { if (e.button != 0) { return; } if (e.target.classlist.contains("icon")) { var wasselected = (e.target.getattribute("id") == "selected"); clearselection(); if (!wasselected) { e.target.setattribute("id", "selected"); } } } function clearselection() { var selected = document.getelementbyid("selected"); if (selected) { selected.removeattribute("id"); } } document.addeventlistener("click", toggleselection); ...
Page inspector keyboard shortcuts - Firefox Developer Tools
dcrumbs bar right arrow right arrow right arrow focus the html pane shift + tab shift + tab shift + tab focus the css pane tab tab tab css pane these shortcuts work when you're in the inspector's css pane. ...
How to - Firefox Developer Tools
ecord a profile to start a new recording, press the stopwatch icon in the recordings pane. to stop, press it again: you can also start and stop recording from the web console, using console.profile() and console.profileend(). save a profile to save a profile, click the link labeled "save" in the recordings pane: load a profile to load a profile, click "import..." and choose the file: clear all loaded profiles to clear all loaded profiles, click "clear". if you do this, you'll lose any loaded profiles that you have not saved. select a tool to switch between the waterfall, call tree, and flame chart tools, use the buttons in the toolbar: configure markers displayed to control which markers are shown in the waterfall, use the button in the toolbar: zoom in to zoom into...
UI Tour - Firefox Developer Tools
note that if you do this, you lose any recordings you have not saved. ...
Web Console Helpers - Firefox Developer Tools
lock. cd() switches javascript evaluation context to a different iframe in the page. this helper accepts multiple different ways of identifying the frame to switch to. you can supply any of the following: a selector string to be passed to document.queryselector to locate the iframe element the iframe element itself the content window inside the iframe see working with iframes. clear() clears the console output area. clearhistory() just like a normal command line, the console command line remembers the commands you've typed. use this function to clear the console's command history. copy() copies the argument to the clipboard. if the argument is a string, it's copied as-is. if the argument is a dom node, its outerhtml is copied. otherwise, json.stringify will be called on...
AesGcmParams - Web APIs
tion carried out with a given key. put another way: never reuse an iv with the same key. the aes-gcm specification recommends that the iv should be 96 bits long, and typically contains bits from a random number generator. section 8.2 of the specification outlines methods for constructing ivs. note that the iv does not have to be secret, just unique: so it is ok, for example, to transmit it in the clear alongside the encrypted message. additionaldata optional a buffersource. this contains additional data that will not be encrypted but will be authenticated along with the encrypted data. if additionaldata is given here then the same data must be given in the corresponding call to decrypt(): if the data given to the decrypt() call does not match the original data, the decryption will throw an...
AnalyserNode.frequencyBinCount - Web APIs
nge-o-matic demo (see app.js lines 128–205 for relevant code). var audioctx = new (window.audiocontext || window.webkitaudiocontext)(); var analyser = audioctx.createanalyser(); analyser.mindecibels = -90; analyser.maxdecibels = -10; ... ...
AnalyserNode.getByteFrequencyData() - Web APIs
. for more examples/information, check out our voice-change-o-matic demo (see app.js lines 128–205 for relevant code). var audioctx = new (window.audiocontext || window.webkitaudiocontext)(); var analyser = audioctx.createanalyser(); ... ...
AnalyserNode.getFloatFrequencyData() - Web APIs
network audiosourcenode.connect(analysernode); analysernode.connect(audioctx.destination); //create 2d canvas const canvas = document.createelement('canvas'); canvas.style.position = 'absolute'; canvas.style.top = 0; canvas.style.left = 0; canvas.width = window.innerwidth; canvas.height = window.innerheight; document.body.appendchild(canvas); const canvasctx = canvas.getcontext('2d'); canvasctx.clearrect(0, 0, canvas.width, canvas.height); function draw() { //schedule next redraw requestanimationframe(draw); //get spectrum data analysernode.getfloatfrequencydata(dataarray); //draw black background canvasctx.fillstyle = 'rgb(0, 0, 0)'; canvasctx.fillrect(0, 0, canvas.width, canvas.height); //draw spectrum const barwidth = (canvas.width / bufferlength) * 2.5; let posx =...
AnalyserNode.getFloatTimeDomainData() - Web APIs
. for more complete applied examples/information, check out our voice-change-o-matic-float-data demo (see the source code too). var audioctx = new (window.audiocontext || window.webkitaudiocontext)(); var analyser = audioctx.createanalyser(); ... ...
AnalyserNode.maxDecibels - Web APIs
nge-o-matic demo (see app.js lines 128–205 for relevant code). var audioctx = new (window.audiocontext || window.webkitaudiocontext)(); var analyser = audioctx.createanalyser(); analyser.mindecibels = -90; analyser.maxdecibels = -10; ... ...
AnalyserNode.minDecibels - Web APIs
nge-o-matic demo (see app.js lines 128–205 for relevant code). var audioctx = new (window.audiocontext || window.webkitaudiocontext)(); var analyser = audioctx.createanalyser(); analyser.mindecibels = -90; analyser.maxdecibels = -10; ... ...
AnalyserNode.smoothingTimeConstant - Web APIs
es are much more jarring. var audioctx = new (window.audiocontext || window.webkitaudiocontext)(); var analyser = audioctx.createanalyser(); analyser.mindecibels = -90; analyser.maxdecibels = -10; analyser.smoothingtimeconstant = 0.85; ... ...
Animation.cancel() - Web APIs
Web › API › Animation › cancel
when an animation is cancelled, its starttime and currenttime are set to null. syntax animation.cancel(); parameters none. return value none. exceptions this method doesn't directly throw exceptions; however, if the animation's playstate is anything but "idle" when cancelled, the current finished promise is rejected with a domexception named aborterror. ...
Animation - Web APIs
Web › API › Animation
sets the timeline associated with this animation. event handlers animation.oncancel gets and sets the event handler for the cancel event. animation.onfinish gets and sets the event handler for the finish event. animation.onremove allows you to set and run an event handler that fires when the animation is removed (i.e., put into an active replace state). methods animation.cancel() clears all keyframeeffects caused by this animation and aborts its playback. animation.commitstyles() commits the end styling state of an animation to the element being animated, even after that animation has been removed. it will cause the end styling state to be written to the element being animated, in the form of properties inside a style attribute. animation.finish() seeks either end of an ...
AudioBuffer.getChannelData() - Web APIs
r channel to get data for. an index value of 0 represents the first channel. if the channel index value is greater than of equal to audiobuffer.numberofchannels, an index_size_err exception will be thrown. return value a float32array. example in the following example we create a two second buffer, fill it with white noise, and then play it via an audiobuffersourcenode. the comments should clearly explain what is going on. you can also run the code live, or view the source. var audioctx = new (window.audiocontext || window.webkitaudiocontext)(); var button = document.queryselector('button'); var pre = document.queryselector('pre'); var myscript = document.queryselector('script'); pre.innerhtml = myscript.innerhtml; // stereo var channels = 2; // create an empty two second stereo buffe...
AudioBufferSourceNode - Web APIs
its parent, audioscheduledsourcenode. methods inherits methods from its parent, audioscheduledsourcenode. audiobuffersourcenode.start() used to schedule playback of the audio data contained in the buffer, or to begin playback immediately. examples in this example, we create a two-second buffer, fill it with white noise, and then play it using an audiobuffersourcenode. the comments should clearly explain what is going on. you can also run the code live, or view the source. var audioctx = new (window.audiocontext || window.webkitaudiocontext)(); // create an empty three-second stereo buffer at the sample rate of the audiocontext var myarraybuffer = audioctx.createbuffer(2, audioctx.samplerate * 3, audioctx.samplerate); // fill the buffer with white noise; //just random values betwe...
AudioListener - Web APIs
doppler effect applied to audiobuffersourcenodes connected downstream — these would be pitched up and down according to the relative speed of the pannernode and the audiolistener. these features had a number of problems: only audiobuffersourcenodes were pitched up or down, not other source nodes. the behavior to adopt when an audiobuffersourcenode was connected to multiple pannernodes was unclear. because the velocity of the panner and the listener were not audioparams, the pitch modification could not be smoothly applied, resulting in audio glitches. because of these issues, these properties and methods have been removed. the setorientation() and setposition() methods have been replaced by setting their property value equivilents. for example setposition(x, y, z) can be achieved by s...
BaseAudioContext.createBuffer() - Web APIs
t it works, and the resized image takes up less space. resampled audio is exactly the same — you save space, but in practice you will be unable to properly reproduce high frequency content (treble sound). now let's look at a more complex createbuffer() example, in which we create a three second buffer, fill it with white noise, and then play it via an audiobuffersourcenode. the comment should clearly explain what is going on. you can also run the code live, or view the source. var audioctx = new (window.audiocontext || window.webkitaudiocontext)(); // create an empty three-second stereo buffer at the sample rate of the audiocontext var myarraybuffer = audioctx.createbuffer(2, audioctx.samplerate * 3, audioctx.samplerate); // fill the buffer with white noise; // just random values between...
BaseAudioContext.createBufferSource() - Web APIs
iobuffers are created using baseaudiocontext.createbuffer or returned by baseaudiocontext.decodeaudiodata when it successfully decodes an audio track. syntax var source = baseaudiocontext.createbuffersource(); returns an audiobuffersourcenode. example in this example, we create a two second buffer, fill it with white noise, and then play it via an audiobuffersourcenode. the comments should clearly explain what is going on. note: you can also run the code live, or view the source. var audioctx = new (window.audiocontext || window.webkitaudiocontext)(); var button = document.queryselector('button'); var pre = document.queryselector('pre'); var myscript = document.queryselector('script'); pre.innerhtml = myscript.innerhtml; // stereo var channels = 2; // create an empty two second ste...
BaseAudioContext.decodeAudioData() - Web APIs
ess callback takes the successfully decoded pcm data, puts it into an audiobuffersourcenode created using audiocontext.createbuffersource(), connects the source to the audiocontext.destination and sets it to loop. the buttons in the example simply run getdata() to load the track and start it playing, and stop it playing, respectively. when the stop() method is called on the source, the source is cleared out. note: you can run the example live (or view the source.) // define variables var audioctx = new (window.audiocontext || window.webkitaudiocontext)(); var source; var pre = document.queryselector('pre'); var myscript = document.queryselector('script'); var play = document.queryselector('.play'); var stop = document.queryselector('.stop'); // use xhr to load an audio track, and // dec...
Using the CSS Painting API - Web APIs
); } h1 { --highcolour: hsla(155, 90%, 60%, 0.7); } h3 { --highcolour: hsla(255, 90%, 60%, 0.5); } h6 { --highcolour: hsla(355, 90%, 60%, 0.3); } and we register our worklet css.paintworklet.addmodule('https://mdn.github.io/houdini-examples/csspaint/intro/03partthree/header-highlight.js'); while you can't edit the worklet itself, you can play around with the css and html. maybe try float and clear on the headers? you could try making the background images above without the css paint api. it is doable, but you would have to declare a different, fairly complex linear gradient for each different color you wanted to create. with the css paint api, one worklet can be re-used, with different colors passed in this case. passing parameters with the css paint api, we not only have access to cus...
CSS Typed Object Model API - Web APIs
tylepropertymap.set() method of stylepropertymap interface that changes the css declaration with the given property to the value given. stylepropertymap.append() method that adds a new css declaration to the stylepropertymap with the given property and value. stylepropertymap.delete() method that removes the css declaration with the given property from the stylepropertymap. stylepropertymap.clear() method that removes all declarations in the stylepropertymap. cssunparsedvalue the cssunparsedvalue interface of the css typed object model api represents property values that reference custom properties. it consists of a list of string fragments and variable references. cssunparsedvalue.cssunparsedvalue() constructor creates a new cssunparsedvalue object which represents property value...
CacheStorage.delete() - Web APIs
global caches property. syntax 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']; even...
CacheStorage.keys() - Web APIs
Web › API › CacheStorage › keys
of all cache objects. you can access 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...
CanvasPattern.setTransform() - Web APIs
lrect(0, 0, 400, 400); };</textarea> var canvas = document.getelementbyid('canvas'); var ctx = canvas.getcontext('2d'); var textarea = document.getelementbyid('code'); var reset = document.getelementbyid('reset'); var edit = document.getelementbyid('edit'); var code = textarea.value; var svg1 = document.getelementbyid('svg1'); var matrix = svg1.createsvgmatrix(); function drawcanvas() { ctx.clearrect(0, 0, canvas.width, canvas.height); eval(textarea.value); } reset.addeventlistener('click', function() { textarea.value = code; drawcanvas(); }); edit.addeventlistener('click', function() { textarea.focus(); }) textarea.addeventlistener('input', drawcanvas); window.addeventlistener('load', drawcanvas); specifications specification status comment html l...
CanvasRenderingContext2D.addHitRegion() - Web APIs
hitregion({id: "eyes"}); // mouth ctx.beginpath(); ctx.arc(100, 110, 50, 0, math.pi, false); ctx.stroke();</textarea> var canvas = document.getelementbyid("canvas"); var ctx = canvas.getcontext("2d"); var textarea = document.getelementbyid("code"); var reset = document.getelementbyid("reset"); var edit = document.getelementbyid("edit"); var code = textarea.value; function drawcanvas() { ctx.clearrect(0, 0, canvas.width, canvas.height); eval(textarea.value); } reset.addeventlistener("click", function() { textarea.value = code; drawcanvas(); }); edit.addeventlistener("click", function() { textarea.focus(); }); canvas.addeventlistener("mousemove", function(event){ if(event.region) { alert("ouch, my eye :("); } }); textarea.addeventlistener("input", drawcanvas); window.add...
CanvasRenderingContext2D.arcTo() - Web APIs
living standard ...
CanvasRenderingContext2D.drawFocusIfNeeded() - Web APIs
as> javascript const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); const button1 = document.getelementbyid('button1'); const button2 = document.getelementbyid('button2'); document.addeventlistener('focus', redraw, true); document.addeventlistener('blur', redraw, true); canvas.addeventlistener('click', handleclick, false); redraw(); function redraw() { ctx.clearrect(0, 0, canvas.width, canvas.height); drawbutton(button1, 20, 20); drawbutton(button2, 20, 80); } function handleclick(e) { // calculate click coordinates const x = e.clientx - canvas.offsetleft; const y = e.clienty - canvas.offsettop; // focus button1, if appropriate drawbutton(button1, 20, 20); if (ctx.ispointinpath(x, y)) { button1.focus(); } // focus button2, if a...
CanvasRenderingContext2D.isPointInPath() - Web APIs
living standard ...
CanvasRenderingContext2D.isPointInStroke() - Web APIs
living standard ...
CanvasRenderingContext2D.lineDashOffset - Web APIs
arching ants the marching ants effect is an animation technique often found in selection tools of computer graphics programs. it helps the user to distinguish the selection border from the image background by animating the border. ...
CanvasRenderingContext2D.miterLimit - Web APIs
="playable-code"> ctx.beginpath(); ctx.moveto(0,0); ctx.linewidth = 15; ctx.lineto(100, 100); ctx.stroke();</textarea> var canvas = document.getelementbyid("canvas"); var ctx = canvas.getcontext("2d"); var textarea = document.getelementbyid("code"); var reset = document.getelementbyid("reset"); var edit = document.getelementbyid("edit"); var code = textarea.value; function drawcanvas() { ctx.clearrect(0, 0, canvas.width, canvas.height); eval(textarea.value); } reset.addeventlistener("click", function() { textarea.value = code; drawcanvas(); }); edit.addeventlistener("click", function() { textarea.focus(); }) textarea.addeventlistener("input", drawcanvas); window.addeventlistener("load", drawcanvas); screenshotlive sample specifications specification status co...
CanvasRenderingContext2D.scrollPathIntoView() - Web APIs
tarea id="code" class="playable-code"> ctx.beginpath(); ctx.rect(10, 10, 30, 30); ctx.scrollpathintoview();</textarea> var canvas = document.getelementbyid("canvas"); var ctx = canvas.getcontext("2d"); var textarea = document.getelementbyid("code"); var reset = document.getelementbyid("reset"); var edit = document.getelementbyid("edit"); var code = textarea.value; function drawcanvas() { ctx.clearrect(0, 0, canvas.width, canvas.height); eval(textarea.value); } reset.addeventlistener("click", function() { textarea.value = code; drawcanvas(); }); edit.addeventlistener("click", function() { textarea.focus(); }) textarea.addeventlistener("input", drawcanvas); window.addeventlistener("load", drawcanvas); specifications specification status comment html l...
CanvasRenderingContext2D.setLineDash() - Web APIs
to an empty array. syntax ctx.setlinedash(segments); parameters segments an array of numbers that specify distances to alternately draw a line and a gap (in coordinate space units). if the number of elements in the array is odd, the elements of the array get copied and concatenated. for example, [5, 15, 25] will become [5, 15, 25, 5, 15, 25]. if the array is empty, the line dash list is cleared and line strokes return to being solid. return value undefined. examples basic example this example uses the setlinedash() method to draw a dashed line above a solid line. html <canvas id="canvas"></canvas> javascript const canvas = document.getelementbyid('canvas'); const ctx = canvas.getcontext('2d'); // dashed line ctx.beginpath(); ctx.setlinedash([5, 15]); ctx.moveto(0, 50); ctx...
A basic ray-caster - Web APIs
fter every interval an update function will repaint the canvas showing the current view. i know i could have started with a simpler example, but i'm sure the canvas tutorial will get to that, and i wanted to see if i could do this. so every update, the raycaster looks to see if you've pressed any keys lately, to conserve calculations by not casting if you're idle. if you have, then the canvas is cleared, the ground and sky are drawn, the camera position and/or orientation are updated, and the rays are cast out. as the rays intersect walls, then they render a vertical sliver of canvas in the color of the wall they've hit, blended with a darker version of the color according to the distance to the wall. the height of the sliver is also modulated by the distance from the camera to the wall, and i...
Basic usage of canvas - Web APIs
« previousnext » let's start this tutorial by looking at the <canvas> html element itself. at the end of this page, you will know how to set up a canvas 2d context and have drawn a first example in your browser. the <canvas> element <canvas id="tutorial" width="150" height="150"></canvas> at first sight a <canvas> looks like the <img> element, with the only clear difference being that it doesn't have the src and alt attributes. indeed, the <canvas> element has only two attributes, width and height. these are both optional and can also be set using dom properties. when no width and height attributes are specified, the canvas will initially be 300 pixels wide and 150 pixels high. the element can be sized arbitrarily by css, but during rendering the image is scaled to fit ...
Drawing text - Web APIs
ayable-code"> ctx.font = "48px serif"; ctx.textbaseline = "hanging"; ctx.stroketext("hello world", 0, 100);</textarea> var canvas = document.getelementbyid('canvas'); var ctx = canvas.getcontext('2d'); var textarea = document.getelementbyid('code'); var reset = document.getelementbyid('reset'); var edit = document.getelementbyid('edit'); var code = textarea.value; function drawcanvas() { ctx.clearrect(0, 0, canvas.width, canvas.height); eval(textarea.value); } reset.addeventlistener('click', function() { textarea.value = code; drawcanvas(); }); edit.addeventlistener('click', function() { textarea.focus(); }) textarea.addeventlistener('input', drawcanvas); window.addeventlistener('load', drawcanvas); advanced text measurements in the case you need to obtain more details abo...
Hit regions and accessibility - Web APIs
easier and lets you route events to dom elements. the api has the following three methods (which are still experimental in current web browsers; check the browser compatibility tables). canvasrenderingcontext2d.addhitregion() adds a hit region to the canvas. canvasrenderingcontext2d.removehitregion() removes the hit region with the specified id from the canvas. canvasrenderingcontext2d.clearhitregions() removes all hit regions from the canvas. you can add a hit region to your path and check for the mouseevent.region property to test if your mouse is hitting your region, for example. <canvas id="canvas"></canvas> <script> var canvas = document.getelementbyid('canvas'); var ctx = canvas.getcontext('2d'); ctx.beginpath(); ctx.arc(70, 80, 10, 0, 2 * math.pi, false); ctx.fill(); ct...
Optimizing canvas - Web APIs
r to optimize rendering. var ctx = canvas.getcontext('2d', { alpha: false }); more tips batch canvas calls together. for example, draw a polyline instead of multiple separate lines. avoid unnecessary canvas state changes. render screen differences only, not the whole new state. avoid the shadowblur property whenever possible. avoid text rendering whenever possible. try different ways to clear the canvas (clearrect() vs. fillrect() vs. resizing the canvas). with animations, use window.requestanimationframe() instead of window.setinterval() . be careful with heavy physics libraries. ...
Pixel manipulation with canvas - Web APIs
the size we want it to. in the zoom canvas we resize a 10×10 pixel crop of the original canvas to 200×200. zoomctx.drawimage(canvas, math.min(math.max(0, x - 5), img.width - 10), math.min(math.max(0, y - 5), img.height - 10), 10, 10, 0, 0, 200, 200); because anti-aliasing is enabled by default, we might want to disable the smoothing to see clear pixels. you can toggle the checkbox to see the effect of the imagesmoothingenabled property (which needs prefixes for different browsers). zoom example <canvas id="canvas" width="300" height="227"></canvas> <canvas id="zoom" width="300" height="227"></canvas> <div> <label for="smoothbtn"> <input type="checkbox" name="smoothbtn" checked="checked" id="smoothbtn"> enable image smoothing </lab...
Canvas tutorial - Web APIs
scripting (usually javascript). this can, for instance, be used to draw graphs, combine photos, or create simple (and not so simple) animations. the images on this page show examples of <canvas> implementations which will be created in this tutorial. this tutorial describes how 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 javas...
Content Index API - Web APIs
an extension to service workers, which allows developers to add urls and metadata of already cached pages, under the scope of the current service worker. the browser can then use these entries to display offline reading to a user. as a developer you can also display these entries within your application. indexed entries do not automatically expire. it's good practice to present an interface for clearing out entries, or periodically remove older entries. the api supports indexing urls corresponding to html documents. a url for a cached media file, for example, can't be indexed directly. instead, you need to provide a url for a page that displays media, and which works offline. interfaces contentindex the contentindex interface provides functionality to register content available of...
Binary strings - Web APIs
Web › API › DOMString › Binary
trings as its input, btoa(): invoking it on a string that contains codepoints greater than 255 will cause a character out of range error. the reason that brought to use utf-16 code units as placeholders for uint8 numbers is that as web applications become more and more powerful (adding features such as audio and video manipulation, access to raw data using websockets, and so forth) it has become clear that there are times when it would be helpful for javascript code to be able to quickly and easily manipulate raw binary data. in the past, this had to be simulated by treating the raw data as a string and using the charcodeat() method to read the bytes from the data buffer (i.e., using binary strings). however, this is slow and error-prone, due to the need for multiple conversions (especially i...
DOMTokenList.value - Web APIs
syntax tokenlist.value; value a domstring examples in the following example we retrieve the list of classes set on a <span> element as a domtokenlist using element.classlist, then write the value of the list to the <span>'s node.textcontent. ...
DataTransferItemList.add() - Web APIs
console.log("... drop: uri = " + s); }); } } } function dragover_handler(ev) { console.log("dragover"); ev.preventdefault(); // set the dropeffect to move ev.datatransfer.dropeffect = "move" } function dragend_handler(ev) { console.log("dragend"); var datalist = ev.datatransfer.items; for (var i = 0; i < datalist.length; i++) { datalist.remove(i); } // clear any remaining drag data datalist.clear(); } result result link specifications specification status comment html living standardthe definition of 'add()' in that specification. living standard html 5.1the definition of 'add()' in that specification. recommendation not included in w3c html5 recommendation ...
DataTransferItemList - Web APIs
tor. properties datatransferitemlist.length read only an unsigned long that is the number of drag items in the list. methods datatransferitemlist.add() adds an item (either a file object or a string) to the drag item list and returns a datatransferitem object for the new item. datatransferitemlist.remove() removes the drag item from the list at the given index. datatransferitemlist.clear() removes all of the drag items from the list. datatransferitemlist.datatransferitem() getter that returns a datatransferitem at the given index. example each of this interface's methods and properties has a reference page, and each reference page has an example of its usage. specifications specification status comment html living standardthe definition of 'datatra...
DedicatedWorkerGlobalScope - Web APIs
ts() imports one or more scripts into the worker's scope. you can specify as many as you'd like, separated by commas. for example: importscripts('foo.js', 'bar.js'); implemented from other places windowbase64.atob() decodes a string of data which has been encoded using base-64 encoding. windowbase64.btoa() creates a base-64 encoded ascii string from a string of binary data. windowtimers.clearinterval() cancels the repeated execution set using windowtimers.setinterval(). windowtimers.cleartimeout() cancels the repeated execution set using windowtimers.settimeout(). windowtimers.setinterval() schedules the execution of a function every x milliseconds. windowtimers.settimeout() sets a delay for executing a function. events message fired when the worker receives a message fr...
Document.execCommand() - Web APIs
hanges the document background color. in stylewithcss mode, it affects the background color of the containing block instead. this requires a <color> value string to be passed in as a value argument. note that internet explorer uses this to set the text background color. bold toggles bold on/off for the selection or at the insertion point. internet explorer uses the <strong> tag instead of <b>. clearauthenticationcache clears all authentication credentials from the cache. contentreadonly makes the content document either read-only or editable. this requires a boolean true/false as the value argument. (not supported by internet explorer.) copy copies the current selection to the clipboard. conditions of having this behavior enabled vary from one browser to another, and have evolved over t...
Document.write() - Web APIs
Web › API › Document › write
syntax document.write(markup); parameters markup a string containing the text to be written to the document. ...
Document - Web APIs
Web › API › Document
ocument.createexpression() compiles an xpathexpression which can then be used for (repeated) evaluations. document.creatensresolver() creates an xpathnsresolver object. document.evaluate() evaluates an xpath expression. extension for html documents the document interface for html documents inherit from the htmldocument interface or, since html5, is extended for such documents: document.clear() in majority of modern browsers, including recent versions of firefox and internet explorer, this method does nothing. document.close() closes a document stream for writing. document.execcommand() on an editable document, executes a formating command. document.getelementsbyname() returns a list of elements with the given name. document.hasfocus() returns true if the focus is current...
Events and the DOM - Web APIs
introduction this chapter describes the dom event model. the event interface itself is described, as well as the interfaces for event registration on nodes in the dom, and event listeners, and several longer examples that show how the various event interfaces relate to one another. there is an excellent diagram that clearly explains the three phases of event flow through the dom in the dom level 3 events draft. also see example 5: event propagation in the examples chapter for a more detailed example of how events move through the dom. registering event listeners there are 3 ways to register event handlers for a dom element. eventtarget.addeventlistener // assuming mybutton is a button element mybutton.addeventlistener('click', greet, false) function greet(event){ // print and have a...
Using the W3C DOM Level 1 Core - Web APIs
ocument by appending it to // the body (which is the parent of para) para.parentnode.appendchild(newelement); } you can see this script as a complete example. how can i learn more? now that you are familiar with the basic concepts of the dom, you may want to learn about the dom level 1 fundamental methods. see also the dom level 1 core specification from the w3c. it's a reasonably clear spec, although it is formal. the main thing that's useful to authors is the description of the different dom objects and all their properties and methods. also see our other dom documentation. original document information author(s): l. david baron <dbaron at dbaron dot org> copyright information: © 1998-2005 by individual mozilla.org contributors; content available under a creative common...
Element.getClientRects() - Web APIs
properties describing the border box, in pixels, with the top-left relative to the top-left of the viewport. for tables with captions, the caption is included even though it's outside the border box of the table. when called on svg elements other than an outer-<svg>, the "viewport" that the resulting rectangles are relative to is the viewport that the element's outer-<svg> establishes (and to be clear, the rectangles are also transformed by the outer-<svg>'s viewbox transform, if any). originally, microsoft intended this method to return a textrectangle object for each line of text. however, the cssom working draft specifies that it returns a domrect for each border box. for an inline element, the two definitions are the same. but for a block element, mozilla will return only a single rectang...
Element.innerHTML - Web APIs
Web › API › Element › innerHTML
ed html or xml fragment is generated based on the current contents of the element, so the markup and formatting of the returned fragment is likely not to match the original page markup. replacing the contents of an element setting the value of innerhtml lets you easily replace the existing contents of an element with new content. for example, you can erase the entire contents of a document by clearing the contents of the document's body attribute: document.body.innerhtml = ""; this example fetches the document's current html markup and replaces the "<" characters with the html entity "&lt;", thereby essentially converting the html into raw text. this is then wrapped in a <pre> element. then the value of innerhtml is changed to this new string. as a result, the document contents are replac...
Event.preventDefault() - Web APIs
+ "\n" ); } } } the displaywarning() function presents a notification of a problem. ...
FontFaceSet - Web APIs
hat a font face set has finished loading. fontfaceset.onloadingerror an eventlistener called whenever an event of type loadingerror is fired, indicating that an error occurred whilst loading a font-face set. methods fontfaceset.add() adds a font to the font set. fontfaceset.check() a boolean that indicates whether a font is loaded, but doesn't initiate a load when it isn't. fontfaceset.clear() removes all manually-added fonts from the font set. css-connected fonts are unaffected. fontfaceset.delete() removes a manually-added font from the font set. css-connected fonts are unaffected. fontfaceset.load() returns a promise which resolves to a list of font-faces for a requested font. specifications specification status comment css font loading module level...
Geolocation - Web APIs
methods the geolocation interface doesn't inherit any method. geolocation.getcurrentposition() secure context determines the device's current location and gives back a geolocationposition object with the data. geolocation.watchposition() secure context returns a long value representing the newly established callback function to be invoked whenever the device location changes. geolocation.clearwatch() secure context removes the particular handler previously installed using watchposition(). specifications specification status comment geolocation api recommendation initial specification. ...
Using the Geolocation API - Web APIs
called repeatedly. note: you can use watchposition() without an initial getcurrentposition() call. const watchid = navigator.geolocation.watchposition((position) => { dosomething(position.coords.latitude, position.coords.longitude); }); the watchposition() method returns an id number that can be used to uniquely identify the requested position watcher; you use this value in tandem with the clearwatch() method to stop watching the user's location. navigator.geolocation.clearwatch(watchid); fine tuning the response both getcurrentposition() and watchposition() accept a success callback, an optional error callback, and an optional positionoptions object. this object allows you to specify whether to enable high accuracy, a maximum age for the returned position value (up until this age i...
Geolocation API - Web APIs
only parameter, providing access information on what went wrong. an optional positionoptions object, which provides options for retrieval of the position data. for further information on geolocation usage, read using the geolocation api. interfaces geolocation the main class of this api — contains methods to retrieve the user's current position, watch for changes in their position, and clear a previously-set watch. geolocationposition represents the position of a user. a geolocationposition instance is returned by a successful call to one of the methods contained inside geolocation, inside a success callback, and contains a timestamp plus a geolocationcoordinates object instance. geolocationcoordinates represents the coordinates of a user's position; a geolocationcoordinates inst...
HTMLBRElement - Web APIs
" height="50" fill="#f4f7f8" stroke="#d4dde4" stroke-width="2px" /><text x="426" y="94" font-size="12px" font-family="consolas,monaco,andale mono,monospace" fill="#4d4e53" text-anchor="middle" alignment-baseline="middle">htmlbrelement</text></a></svg></div> a:hover text { fill: #0095dd; pointer-events: all;} properties inherits properties from its parent, htmlelement. htmlbrelement.clear is a domstring indicating the flow of text around floating objects. methods no specific method; inherits methods from its parent, htmlelement. specifications specification status comment html living standardthe definition of 'htmlbrelement' in that specification. living standard no change from html5 html5the definition of 'htmlbrelement' in that spec...
HTMLCanvasElement.getContext() - Web APIs
this is the default value. "high-performance": prioritizes rendering performance over power consumption. "low-power": prioritizes power saving over rendering performance. premultipliedalpha: boolean that indicates that the page compositor will assume the drawing buffer contains colors with pre-multiplied alpha. preservedrawingbuffer: if the value is true the buffers will not be cleared and will preserve their values until cleared or overwritten by the author. stencil: boolean that indicates that the drawing buffer has a stencil buffer of at least 8 bits. return value a renderingcontext which is either a canvasrenderingcontext2d for "2d", webglrenderingcontext for "webgl" and "experimental-webgl", webgl2renderingcontext for "webgl2" or imagebitmaprenderingcontex...
HTMLCanvasElement.toDataURL() - Web APIs
living standard no change since the latest snapshot, html5 html 5.1the definition of 'htmlc...
HTMLInputElement: search event - Web APIs
search there are several ways a search can be initiated, such as by pressing enter while the <input> is focused, or, if the incremental attribute is present, after a ua-defined timeout elapses since the most recent keystroke (with new keystrokes resetting the timeout so the firing of the event is debounced). current ua implementations of <input type="search"> have an additional control to clear the field. using this control also fires the search event. in that case the value of the <input> element will be the empty string. examples // addeventlistener version const input = document.queryselector('input[type="search"]'); input.addeventlistener('search', () => { console.log("the term searched for was " + input.value); }) // onsearch version const input = document.queryselector('input...
HTMLMediaElement.play() - Web APIs
ybutton() { if (videoelem.paused) { playvideo(); } else { videoelem.pause(); playbutton.classlist.remove("playing"); } } in this example, playback of video is toggled off and on by the async playvideo() function. it tries to play the video, and if successful sets the class name of the playbutton element to "playing". if playback fails to start, the playbutton element's class is cleared, restoring its default appearance. this ensures that the play button matches the actual state of playback by watching for the resolution or rejection of the promise returned by play(). when this example is executed, it begins by collecting references to the <video> element as well as the <button> used to toggle playback on and off. it then sets up an event handler for the click event on the pl...
Drag Operations - Web APIs
pplication whereas the other types can include just a single url or text version. note that both the text/uri-list and text/plain contain the same data in this example. this will often be true, but doesn't need to be the case. if you attempt to add data twice with the same format, the new data will replace the old data, but in the same position within the list of types as the old data. you can clear the data using the cleardata() method, which takes one argument: the type of the data to remove. event.datatransfer.cleardata("text/uri-list"); the type argument to the cleardata() method is optional. if the type is not specified, the data associated with all types is removed. if the drag contains no drag data items, or all of the items have been subsequently cleared, then no drag will occur. ...
HTML Drag and Drop API - Web APIs
datatransferitem object represents a single drag item, each with a kind property (either string or file) and a type property for the data item's mime type. the datatransferitem object also has methods to get the drag item's data. the datatransferitemlist object is a list of datatransferitem objects. the list object has methods to add a drag item to the list, remove a drag item from the list, and clear the list of all drag items. a key difference between the datatransfer and datatransferitem interfaces is that the former uses the synchronous getdata() method to access a drag item's data, but the latter instead uses the asynchronous getasstring() method. note: dragevent and datatransfer are broadly supported on desktop browsers. however, the datatransferitem and datatransferitemlist interfaces...
Headers - Web APIs
Web › API › Headers
eader. headers.keys() returns an iterator allowing you to go through all keys of the key/value pairs contained in this object. headers.set() sets a new value for an existing header inside a headers object, or adds the header if it does not already exist. headers.values() returns an iterator allowing you to go through all values of the key/value pairs contained in this object. note: to be clear, the difference between headers.set() and headers.append() is that if the specified header does already exist and does accept multiple values, headers.set() will overwrite the existing value with the new one, whereas headers.append() will append the new value onto the end of the set of values. see their dedicated pages for example code. note: all of the headers methods will throw a typeerror i...
IDBDatabase: close event - Web APIs
note that it is not fired if the database connection is closed normally using idbdatabase.close(). ...
IDBObjectStore.delete() - Web APIs
the delete() method of the idbobjectstore interface returns an idbrequest object, and, in a separate thread, deletes the specified record or records. either a key or an idbkeyrange can be passed, allowing one or multiple records to be deleted from a store. to delete all records in a store, use idbobjectstore.clear. bear in mind that if you are using a idbcursor, you can use the idbcursor.delete() method to more efficiently delete the current record — without having to explicitly look up the record's key. note: this feature is available in web workers. syntax var request = objectstore.delete(key); var request = objectstore.delete(keyrange); parameters key the key of the record to be deleted, or an idbkeyrange to delete all records with keys in range. return value an idbreque...
IDBObjectStore.put() - Web APIs
to the key for the stored record, and the transaction set to the transaction in which this object store is opened. the put method is an update or insert method. see the idbobjectstore.add method for an insert only method. bear in mind that if you have a idbcursor to the record you want to update, updating it with idbcursor.update() is preferable to using idbobjectstore.put(). doing so makes it clear that an existing record will be updated, instead of a new record being inserted. note: this feature is available in web workers. syntax let request = objectstore.put(item); let request = objectstore.put(item, key); parameters item the item you wish to update (or insert). key optional the primary key of the record you want to update (e.g. from idbcursor.primarykey). this is only needed f...
ImageCapture - Web APIs
og(error)); } /* utils */ function drawcanvas(canvas, img) { canvas.width = getcomputedstyle(canvas).width.split('px')[0]; canvas.height = getcomputedstyle(canvas).height.split('px')[0]; let ratio = math.min(canvas.width / img.width, canvas.height / img.height); let x = (canvas.width - img.width * ratio) / 2; let y = (canvas.height - img.height * ratio) / 2; canvas.getcontext('2d').clearrect(0, 0, canvas.width, canvas.height); canvas.getcontext('2d').drawimage(img, 0, 0, img.width, img.height, x, y, img.width * ratio, img.height * ratio); } document.queryselector('video').addeventlistener('play', function() { document.queryselector('#grabframebutton').disabled = false; document.queryselector('#takephotobutton').disabled = false; }); specifications specific...
Browser storage limits and eviction criteria - Web APIs
it was, say, 8 mb, then the group limit would also be 8 mb. note: if the group limit is exceeded, or if origin eviction couldn't free enough space, the browser will throw a quotaexceedederror. note: in chrome the soft and hard storage quota limits has changed since m66. more information can be found here. lru policy when the available disk space is filled up, the quota manager will start clearing out data based on an lru policy — the least recently used origin will be deleted first, then the next one, until the browser is no longer over the limit. we track the "last access time" for each origin using temporary storage. once the global limit for temporary storage is reached (more on the limit later), we try to find all currently unused origins (i.e., ones with no tabs/apps open that ...
IndexedDB API - Web APIs
you can access stored data within a domain, you cannot access data across different domains. synchronous and asynchronous operations performed using indexeddb are done asynchronously, so as not to block applications. indexeddb originally included both synchronous and asynchronous apis. the synchronous api was intended for use only with web workers but was removed from the spec because it was unclear whether it was needed. however, the synchronous api may be reintroduced if there is enough demand from web developers. storage limits and eviction criteria there are a number of web technologies that store data of one kind or another on the client side (i.e. on your local disk). indexeddb is most commonly talked about. the process by which the browser works out how much space to allocate to web...
IntersectionObserver.takeRecords() - Web APIs
an array of intersectionobserverentry objects, one for each targeted element which has experienced an intersection change since the last time the intersections were checked, either explicitly through a call to this method or implicitly by an automatic call to the observer's callback. note: if you use the callback to monitor these changes, you don't need to call this method. calling this method clears the pending intersection list, so the callback will not be run. syntax intersectionobserverentries = intersectionobserver.takerecords(); parameters none. return value an array of intersectionobserverentry objects, one for each target element whose intersection with the root has changed since the last time the intersections were checked. examples <<<...>>> specifications sp...
KeyboardEvent: code values - Web APIs
controlright" kvk_function (0x3f) "fn" (no events fired actually) "" (no events fired actually) kvk_f17 (0x40) "f17" "f17" kvk_ansi_keypaddecimal (0x41) "numpaddecimal" "numpaddecimal" kvk_ansi_keypadmultiply (0x43) "numpadmultiply" "numpadmultiply" kvk_ansi_keypadplus (0x45) "numpadadd" "numpadadd" kvk_ansi_keypadclear (0x47) "numlock" "numlock" kvk_volumeup (0x48) "audiovolumeup" (was "volumeup" until firefox 48) "audiovolumeup" (was "volumeup" until chrome 50) kvk_volumedown (0x49) "audiovolumedown" (was "volumedown" until firefox 49) "audiovolumedown" (was "volumedown" until chrome 50) kvk_mute (0x4a) "audiovolumemute" (was "volumemute" until firefox 49) "au...
MIDIInputMap - Web APIs
the midiinputmap read-only interface of the web midi api provides a map-like interface to the currently available midi input ports. though it works generally like a map, because it is read-only it does not contain clear(), delete(), or set() functions. specifications specification status comment web midi api working draft initial definition. ...
MIDIOutputMap - Web APIs
the midioutputmap read-only interface of the web midi api provides a map-like interface to the currently available midi output ports. although it works like a map, because it is read-only, it does not contain clear(), delete(), or set() functions. specifications specification status comment web midi api working draft initial definition. ...
MediaDeviceInfo.deviceId - Web APIs
for private browsing, a different identifier is used that is not persisted across sessions. syntax var deviceid = mediadeviceinfo.deviceid value a domstring. ...
MediaDeviceInfo - Web APIs
obtained by calling navigator.mediadevices.enumeratedevices() is an array of mediadeviceinfo objects, one per media device. properties mediadeviceinfo.deviceidread only returns a domstring that is an identifier for the represented device that is persisted across sessions. it is un-guessable by other applications and unique to the origin of the calling application. it is reset when the user clears cookies (for private browsing, a different identifier is used that is not persisted across sessions). mediadeviceinfo.groupidread only returns a domstring that is a group identifier. two devices have the same group identifier if they belong to the same physical device — for example a monitor with both a built-in camera and a microphone. mediadeviceinfo.kindread only returns an enumerated...
MediaDevices.getUserMedia() - Web APIs
here, indicate we need the ability to use both camera and microphone: <iframe src="https://mycode.example.net/etc" allow="camera;microphone"> </iframe> read our guide, using feature policy, to learn more about how it works. encryption based security the getusermedia() method is only available in secure contexts. a secure context is one ...
MediaSource - Web APIs
vent handler for the sourceclose event. mediasource.onsourceended the event handler for the sourceended event. mediasource.onsourceopen the event handler for the sourceopen event. methods inherits methods from its parent interface, eventtarget. mediasource.addsourcebuffer() creates a new sourcebuffer of the given mime type and adds it to the mediasource.sourcebuffers list. mediasource.clearliveseekablerange() clears a seekable range previously set with a call to setliveseekablerange(). mediasource.endofstream() signals the end of the stream. mediasource.removesourcebuffer() removes the given sourcebuffer from the mediasource.sourcebuffers list. mediasource.setliveseekablerange() sets the range that the user can seek to in the media element. static methods mediasource.ist...
MediaStreamTrack.applyConstraints() - Web APIs
lyconstraints([constraints]) parameters constraints optional a mediatrackconstraints object listing the constraints to apply to the track's constrainable properties; any existing constraints are replaced with the new values specified, and any constrainable properties not included are restored to their default constraints. if this parameter is omitted, all currently set custom constraints are cleared. this object represents the basic set of constraints that must apply for the promise to resolve. the object may contain an advanced property containing an array of additional mediatrackconstrants objects, which are treated as exact requires. return value a promise which resolves when the constraints have been successfully applied. if the constraints cannot be applied, the promise is rejecte...
Recording a media element - Web APIs
let preview = document.getelementbyid("preview"); let recording = document.getelementbyid("recording"); let startbutton = document.getelementbyid("sta...
Microsoft API extensions - Web APIs
nevent msmanipulationstatechanged msmanipulationviewsenabled mspointerhover media apis htmlvideoelement.msframestep() htmlvideoelement.mshorizontalmirror htmlvideoelement.msinsertvideoeffect() htmlvideoelement.msislayoutoptimalforplayback htmlvideoelement.msisstereo3d htmlvideoelement.mszoom htmlaudioelement.msaudiocategory htmlaudioelement.msaudiodevicetype htmlmediaelement.mscleareffects() htmlmediaelement.msinsertaudioeffect() mediaerror.msextendedcode msgraphicstrust msgraphicstruststatus msisboxed msplaytodisabled msplaytopreferredsourceuri msplaytoprimary msplaytosource msrealtime mssetmediaprotectionmanager mssetvideorectangle msstereo3dpackingmode msstereo3drendermode onmsvideoformatchanged onmsvideoframestepcompleted onmsvideooptimallayoutchanged m...
Navigator.clipboard - Web APIs
).innertext = cliptext); this snippet replaces the contents of the element whose class is "cliptext" with the text contents of the clipboard. perhaps this code is being used in a browser extension that displays the current clipboard contents, automatically updating periodically or when specific events fire. if the clipboard is empty or doesn't contain text, the "cliptext" element's contents are cleared. this happens because readtext() returns an empty string if the clipboard is empty or doesn't contain text. specifications specification status comment clipboard api and eventsthe definition of 'navigator.clipboard' in that specification. working draft initial definition. ...
Navigator.requestMediaKeySystemAccess() - Web APIs
s a general rule, this function should be called only when it's about time to create and use a mediakeys object by calling the returned mediakeysystemaccess object's createmediakeys() method. syntax ​promise = navigator.requestmediakeysystemaccess(keysystem, supportedconfigurations); parameters keysystem a domstring identifying the key system. for example com.example.somesystem or org.w3.clearkey. supportedconfigurations a non-empty array of mediakeysystemconfiguration objects. the first element with a satisfiable configuration will be used. return value a promise that, when resolved, delivers a mediakeysystemaccess object to your fulfillment handler function. the fulfillment handler receives as input just one parameter: mediakeysystemaccess a mediakeysystemaccess object repre...
Notification.close() - Web APIs
n to remove the notification when the relevant content has been read on the webpage. function spawnnotification(thebody, theicon, thetitle) { var options = { body: thebody, icon: theicon }; var n = new notification(thetitle,options); document.addeventlistener('visibilitychange', function() { if (document.visibilitystate === 'visible') { // the tab has become visible so clear the now-stale notification. n.close(); } }); } specifications specification status comment notifications api living standard living standard ...
OVR_multiview2.framebufferTextureMultiviewOVR() - Web APIs
framebuffertexturemultiviewovr(target, attachment, texture, level, baseviewindex, numviews); parameters target a glenum specifying the binding point (target). possible values: gl.framebuffer: collection buffer data storage of color, alpha, depth and stencil buffers used to render an image. gl.draw_framebuffer: equivalent to gl.framebuffer. used as a destination for drawing, rendering, clearing, and writing operations. gl.read_framebuffer: used as a source for reading operations. attachment a glenum specifying the attachment point for the texture. possible values: gl.color_attachment0: attaches the texture to the framebuffer's color buffer. gl.depth_attachment: attaches the texture to the framebuffer's depth buffer. gl.stencil_attachment: attaches the texture to the f...
OffscreenCanvas.getContext() - Web APIs
16 bits. stencil: boolean that indicates that the drawing buffer has a stencil buffer of at least 8 bits. antialias: boolean that indicates whether or not to perform anti-aliasing. premultipliedalpha: boolean that indicates that the page compositor will assume the drawing buffer contains colors with pre-multiplied alpha. preservedrawingbuffer: if the value is true the buffers will not be cleared and will preserve their values until cleared or overwritten by the author. failifmajorperformancecaveat: boolean that indicates if a context will be created if the system performance is low. return value a renderingcontext which is either a canvasrenderingcontext2d for "2d", webglrenderingcontext for "webgl" and "experimental-webgl", webgl2renderingcontext for "webgl2" and ...
PannerNode.coneInnerAngle - Web APIs
e sound volume decreases gradually // if coneouterangle == 45 and coneinnerangle == 30, it means that when the sound is rotated // by between 15 (30/2) and 22.5 (45/2) degrees either direction, // the volume will decrease gradually panner.coneouterangle = 45; // this value determines the volume of the sound outside of both inner and outer cone // setting it to 0 means there is no sound, so we can clearly hear when we leave the cone // 0 is also the default panner.coneoutergain = 0; // increase the z position to ensure the cone has an effect // (otherwise the sound is located at the same position as the listener) panner.positionz.setvalueattime(1, context.currenttime); having set up the pannernode, we can now schedule some updates to its y-axis rotation: // calculate the vector for no rotation...
PannerNode.coneOuterAngle - Web APIs
e sound volume decreases gradually // if coneouterangle == 45 and coneinnerangle == 30, it means that when the sound is rotated // by between 15 (30/2) and 22.5 (45/2) degrees either direction, // the volume will decrease gradually panner.coneouterangle = 45; // this value determines the volume of the sound outside of both inner and outer cone // setting it to 0 means there is no sound, so we can clearly hear when we leave the cone // 0 is also the default panner.coneoutergain = 0; // increase the z position to ensure the cone has an effect // (otherwise the sound is located at the same position as the listener) panner.positionz.setvalueattime(1, context.currenttime); having set up the pannernode, we can now schedule some updates to its y-axis rotation: // calculate the vector for no rotation...
PannerNode.coneOuterGain - Web APIs
e sound volume decreases gradually // if coneouterangle == 45 and coneinnerangle == 30, it means that when the sound is rotated // by between 15 (30/2) and 22.5 (45/2) degrees either direction, // the volume will decrease gradually panner.coneouterangle = 45; // this value determines the volume of the sound outside of both inner and outer cone // setting it to 0 means there is no sound, so we can clearly hear when we leave the cone // 0 is also the default panner.coneoutergain = 0; // increase the z position to ensure the cone has an effect // (otherwise the sound is located at the same position as the listener) panner.positionz.setvalueattime(1, context.currenttime); having set up the pannernode, we can now schedule some updates to its y-axis rotation: // calculate the vector for no rotation...
PannerNode.orientationX - Web APIs
e sound volume decreases gradually // if coneouterangle == 45 and coneinnerangle == 30, it means that when the sound is rotated // by between 15 (30/2) and 22.5 (45/2) degrees either direction, // the volume will decrease gradually panner.coneouterangle = 45; // this value determines the volume of the sound outside of both inner and outer cone // setting it to 0 means there is no sound, so we can clearly hear when we leave the cone // 0 is also the default panner.coneoutergain = 0; // increase the z position to ensure the cone has an effect // (otherwise the sound is located at the same position as the listener) panner.positionz.setvalueattime(1, context.currenttime); having set up the pannernode, we can now schedule some updates to its y-axis rotation: // calculate the vector for no rotation...
PannerNode.orientationY - Web APIs
e sound volume decreases gradually // if coneouterangle == 45 and coneinnerangle == 30, it means that when the sound is rotated // by between 15 (30/2) and 22.5 (45/2) degrees either direction, // the volume will decrease gradually panner.coneouterangle = 45; // this value determines the volume of the sound outside of both inner and outer cone // setting it to 0 means there is no sound, so we can clearly hear when we leave the cone // 0 is also the default panner.coneoutergain = 0; // increase the z position to ensure the cone has an effect // (otherwise the sound is located at the same position as the listener) panner.positionz.setvalueattime(1, context.currenttime); having set up the pannernode, we can now schedule some updates to its y-axis rotation: // calculate the vector for no rotation...
PannerNode.orientationZ - Web APIs
e sound volume decreases gradually // if coneouterangle == 45 and coneinnerangle == 30, it means that when the sound is rotated // by between 15 (30/2) and 22.5 (45/2) degrees either direction, // the volume will decrease gradually panner.coneouterangle = 45; // this value determines the volume of the sound outside of both inner and outer cone // setting it to 0 means there is no sound, so we can clearly hear when we leave the cone // 0 is also the default panner.coneoutergain = 0; // increase the z position to ensure the cone has an effect // (otherwise the sound is located at the same position as the listener) panner.positionz.setvalueattime(1, context.currenttime); having set up the pannernode, we can now schedule some updates to its y-axis rotation: // calculate the vector for no rotation...
PannerNode - Web APIs
ner attribute.) pannernode.setorientation() defines the direction the audio source is playing in. pannernode.setvelocity() defines the velocity vector of the audio source — how fast it is moving and in what direction. in a previous version of the specification, the pannernode had a velocity that could pitch up or down audiobuffersourcenodes connected downstream. this feature was not clearly specified and had a number of issues, so it was removed from the specification. examples in the following example, you can see an example of how the createpanner() method, audiolistener and pannernode would be used to control audio spatialisation. generally you will define the position in 3d space that your audio listener and panner (source) occupy initially, and then update the position of...
performance.mark() - Web APIs
Web › API › Performance › mark
formance.mark("monkey"); performance.mark("monkey"); performance.mark("dog"); performance.mark("dog"); // get all of the performancemark entries. const allentries = performance.getentriesbytype("mark"); console.log(allentries.length); // 6 // get all of the "monkey" performancemark entries. const monkeyentries = performance.getentriesbyname("monkey"); console.log(monkeyentries.length); // 2 // clear out all of the marks. performance.clearmarks(); specifications specification status comment user timing level 2the definition of 'mark()' in that specification. working draft clarifies mark() processing model. user timingthe definition of 'mark()' in that specification. recommendation basic definition. ...
performance.measure() - Web APIs
markernamea, markernameb); performance.measure("measure a to now", markernamea); performance.measure("measure from navigation start to b", undefined, markernameb); performance.measure("measure from the start of navigation to now"); // pull out all of the measurements. console.log(performance.getentriesbytype("measure")); // finally, clean up the entries. performance.clearmarks(); performance.clearmeasures(); }, 1000); }, 1000); specifications specification status comment user timing level 2the definition of 'measure()' in that specification. working draft clarifies measure() processing model. user timingthe definition of 'measure()' in that specification. recommendation basic definition. ...
Using Pointer Events - Web APIs
ointerid); var idx = ongoingtouchindexbyid(evt.pointerid); ongoingtouches.splice(idx, 1); // remove it; we're done } since the idea is to immediately abort the touch, we simply remove it from the ongoing touch list without drawing a final line segment. convenience functions this example uses two convenience functions that should be looked at briefly to help make the rest of the code more clear. selecting a color for each touch in order to make each touch's drawing look different, the colorfortouch() function is used to pick a color based on the touch's unique identifier. this identifier is an opaque number, but we can at least rely on it differing between the currently-active touches. function colorfortouch(touch) { var r = touch.pointerid % 16; var g = math.floor(touch.pointeri...
Web Push API Notifications best practices - Web APIs
ones very sparingly, since they can be the most annoying. your notifications should be assistive, not disruptive. building trust some studies have shown that as many as 60% of push notifications are blocked. allowing your site to push notifications in realtime requires trust. you can build trust by having a well-designed website that provides good content that shows respect for the user, and a clear value to accepting push notifications. browser mitigations because of abuses of push notifications in the past, web browser developers have begun to implement strategies to help mitigate this problem. for 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 ...
RTCDTMFSender.insertDTMF() - Web APIs
can send tones at any time. calling insertdtmf() will append the specified tones to the end of the current tone buffer, so that those tones play after the previously-enqueued tones. syntax rtcdtmfsender.insertdtmf(tones[, duration[, intertonegap]]); parameters tones a domstring containing the dtmf codes to be transmitted to the recipient. specifying an empty string as the tones parameter clears the tone buffer, aborting any currently queued tones. a "," character inserts a two second delay. duration optional the amount of time, in milliseconds, that each dtmf tone should last. this value must be between 40 ms and 6000 ms (6 seconds), inclusive. the default is 100 ms. intertonegap optional the length of time, in milliseconds, to wait between tones. the browser will enforce a minimum...
Range.selectNodeContents() - Web APIs
elect or deselect the contents of this paragraph.</p> <button id="select-button">select paragraph</button> <button id="deselect-button">deselect paragraph</button> javascript const p = document.getelementbyid('p'); const selectbutton = document.getelementbyid('select-button'); const deselectbutton = document.getelementbyid('deselect-button'); selectbutton.addeventlistener('click', e => { // clear any current selection const selection = window.getselection(); selection.removeallranges(); // select paragraph const range = document.createrange(); range.selectnodecontents(p); selection.addrange(range); }); deselectbutton.addeventlistener('click', e => { const selection = window.getselection(); selection.removeallranges(); }); result specifications specification...
ReadableStream.ReadableStream() - Web APIs
estream({ start(controller) { interval = setinterval(() => { let string = randomchars(); // add the string to the stream controller.enqueue(string); // show it on the screen let listitem = document.createelement('li'); listitem.textcontent = string; list1.appendchild(listitem); }, 1000); button.addeventlistener('click', function() { clearinterval(interval); fetchstream(); controller.close(); }) }, pull(controller) { // we don't really need a pull in this example }, cancel() { // this is called if the reader cancels, // so we should stop generating strings clearinterval(interval); } }); specifications specification status comment streamsthe definition of 'readables...
ReadableStreamDefaultController.close() - Web APIs
estream({ start(controller) { interval = setinterval(() => { let string = randomchars(); // add the string to the stream controller.enqueue(string); // show it on the screen let listitem = document.createelement('li'); listitem.textcontent = string; list1.appendchild(listitem); }, 1000); button.addeventlistener('click', function() { clearinterval(interval); fetchstream(); controller.close(); }) }, pull(controller) { // we don't really need a pull in this example }, cancel() { // this is called if the reader cancels, // so we should stop generating strings clearinterval(interval); } }); specifications specification status comment streamsthe definition of 'close()' ...
ReadableStreamDefaultController.enqueue() - Web APIs
estream({ start(controller) { interval = setinterval(() => { let string = randomchars(); // add the string to the stream controller.enqueue(string); // show it on the screen let listitem = document.createelement('li'); listitem.textcontent = string; list1.appendchild(listitem); }, 1000); button.addeventlistener('click', function() { clearinterval(interval); fetchstream(); controller.close(); }) }, pull(controller) { // we don't really need a pull in this example }, cancel() { // this is called if the reader cancels, // so we should stop generating strings clearinterval(interval); } }); specifications specification status comment streamsthe definition of 'enqueue()...
ReadableStreamDefaultController - Web APIs
estream({ start(controller) { interval = setinterval(() => { let string = randomchars(); // add the string to the stream controller.enqueue(string); // show it on the screen let listitem = document.createelement('li'); listitem.textcontent = string; list1.appendchild(listitem); }, 1000); button.addeventlistener('click', function() { clearinterval(interval); fetchstream(); controller.close(); }) }, pull(controller) { // we don't really need a pull in this example }, cancel() { // this is called if the reader cancels, // so we should stop generating strings clearinterval(interval); } }); specifications specification status comment streamsthe definition of 'readables...
Resource Timing API - Web APIs
ype of resource that initiated the performance entry such as "css" for a css resource, "xmlhttprequest" for an xmlhttprequest and "img" for an image (such as a jpeg). if the current context is a worker, the workerstart property can be used to obtain a domhighrestimestamp when the worker was started. methods the resource timing api includes two methods that extend the performance interface. the clearresourcetimings() method removes all "resource" type performance entries from the browser's resource performance entry buffer. the setresourcetimingbuffersize() method sets the resource performance entry buffer size to the specified number of resource performance entries. the performanceresourcetiming interface's tojson() method returns a json serialization of a "resource" type performance entry.
Using Service Workers - Web APIs
some useful tools related to service workers: you can navigate to about:debugging to see what sws are registered and update/remove them. when testing you can get around the https restriction by checking the "enable service workers over http (when toolbox is open)" option in the firefox developer tools settings. the "forget" button, available in firefox's customization options, can be used to clear service workers and their caches (bug 1252998). note: you may serve your app from http://localhost (e.g. using me@localhost:/my/app$ python -m simplehttpserver) for local development. see security considerations ...
SharedWorkerGlobalScope - Web APIs
ts() imports one or more scripts into the worker's scope. you can specify as many as you'd like, separated by commas. for example: importscripts('foo.js', 'bar.js'); implemented from other places windowbase64.atob() decodes a string of data which has been encoded using base-64 encoding. windowbase64.btoa() creates a base-64 encoded ascii string from a string of binary data. windowtimers.clearinterval() cancels the repeated execution set using windowtimers.setinterval(). windowtimers.cleartimeout() cancels the repeated execution set using windowtimers.settimeout(). windowtimers.setinterval() schedules the execution of a function every x milliseconds. windowtimers.settimeout() sets a delay for executing a function. events listen to this event using addeventlistener() or by ass...
SourceBuffer.removeAsync() - Web APIs
); parameters start a double representing the start of the time range, in seconds. end a double representing the end of the time range, in seconds. return value a promise whose fulfillment handler is executed once the buffers in the specified time range have been removed from the sourcebuffer. example this example establishes an asynchronous function, emptysourcebuffer(), which simply clears the contents of the specified sourcebuffer. async function emptysourcebuffer(msbuffer) { await msbuffer.removeasync(0, infinity).catch(function(e) { handleexception(e); } } specifications not currently part of the mse specification. specification status comment media source extensions recommendation initial definition. ...
SpeechSynthesisVoice.default - Web APIs
syntax var amidefault = speechsynthesisvoiceinstance.default; value a boolean. ...
Storage - Web APIs
Web › API › Storage
) when passed a number n, this method will return the name of the nth key in the storage. storage.getitem() when passed a key name, will return that key's value. storage.setitem() when passed a key name and value, will add that key to the storage, or update that key's value if it already exists. storage.removeitem() when passed a key name, will remove that key from the storage. storage.clear() when invoked, will empty all keys out of the storage. examples here we access a storage object by calling localstorage. we first test whether the local storage contains data items using !localstorage.getitem('bgcolor'). if it does, we run a function called setstyles() that grabs the data items using storage.getitem() and uses those values to update page styles. if it doesn't, we run another...
StorageEvent - Web APIs
overview void initstorageevent( in domstring type, in boolean canbubble, in boolean cancelable, in domstring key, in domstring oldvalue, in domstring newvalue, in usvstring url, in storage storagearea ); attributes attribute type description key domstring represents the key changed. the key attribute is null when the change is caused by the storage clear() method. read only. newvalue domstring the new value of the key. the newvalue is null when the change has been invoked by storage clear() method or the key has been removed from the storage. read only. oldvalue domstring the original value of the key. the oldvalue is null when the key has been newly added and therefore doesn't have any previous value. read only. ...
StorageManager.persist() - Web APIs
ue if permission is granted and box mode is persistent, and false otherwise. syntax navigator.storage.persist().then(function(persistent) { ... }) parameters none. return value a promise that resolves to a boolean. example if (navigator.storage && navigator.storage.persist) navigator.storage.persist().then(function(persistent) { if (persistent) console.log("storage will not be cleared except by explicit user action"); else console.log("storage may be cleared by the ua under storage pressure."); }); specifications specification status comment storagethe definition of 'persist' in that specification. living standard initial definition. browser compatibility the compatibility table on this page is generated from structured dat...
StorageManager.persisted() - Web APIs
mise that resolves to true if box mode is persistent for your site's storage. syntax navigator.storage.persisted().then(function(persistent) { ... }) parameters none. returns a promise that resolves to a boolean. example if (navigator.storage && navigator.storage.persist) navigator.storage.persisted().then(function(persistent) { if (persistent) console.log("storage will not be cleared except by explicit user action"); else console.log("storage may be cleared by the ua under storage pressure."); }); specifications specification status comment storagethe definition of 'persisted' in that specification. living standard initial definition. ...
Using readable streams - Web APIs
ablestream({ start(controller) { interval = setinterval(() => { let string = randomchars(); // add the string to the stream controller.enqueue(string); // show it on the screen let listitem = document.createelement('li'); listitem.textcontent = string; list1.appendchild(listitem); }, 1000); button.addeventlistener('click', function() { clearinterval(interval); readstream(); controller.close(); }) }, pull(controller) { // we don't really need a pull in this example }, cancel() { // this is called if the reader cancels, // so we should stop generating strings clearinterval(interval); } }); in the readstream() function itself, we lock a reader to the stream using readablestream.getreader(), the...
StylePropertyMap - Web APIs
-baseline="middle">stylepropertymap</text></a></svg></div> a:hover text { fill: #0095dd; pointer-events: all;} properties inherits properties from its parent, stylepropertymapreadonly. methods inherits methods from its parent, stylepropertymapreadonly. stylepropertymap.append() adds a new css declaration to the stylepropertymap with the given property and value. stylepropertymap.clear() removes all declarations in the stylepropertymap. stylepropertymap.delete() removes the css declaration with the given property. stylepropertymap.set() changes the css declaration with the given property. specifications specification status comment css typed om level 1the definition of 'stylepropertymap' in that specification. working draft initial definiti...
SubtleCrypto - Web APIs
stem completely ineffective. if you're not sure you know what you are doing, you probably shouldn't be using this api. properties this interface doesn't inherit any properties, as it has no parent interface. methods this interface doesn't inherit any methods, as it has no parent interface. subtlecrypto.encrypt() returns a promise that fufills with the encrypted data corresponding to the clear text, algorithm, and key given as parameters. subtlecrypto.decrypt() returns a promise that fulfills with the clear data corresponding to the encrypted text, algorithm, and key given as parameters. subtlecrypto.sign() returns a promise that fulfills with the signature corresponding to the text, algorithm, and key given as parameters. subtlecrypto.verify() returns a promise that fulfills wit...
Text.wholeText - Web APIs
Web › API › Text › wholeText
hich replacewholetext() is called, and we’re changing the remaining one to the new text. what we have now is this: <p>thru-hiking is great, but <a href="http://en.wikipedia.org/wiki/absentee_ballot">casting a ballot</a> is tricky.</p> some uses of the whole-text functionality may be better served by using node.textcontent, or the longstanding element.innerhtml; that’s fine and probably clearer in most circumstances. if you have to work with mixed content within an element, as seen here, wholetext and replacewholetext() may be useful. replacewholetext() is obsolete. specifications specification status comment domthe definition of 'text.wholetext' in that specification. living standard no significant change. document object model (dom) level ...
Touch events - Web APIs
ar idx = ongoingtouchindexbyid(touches[i].identifier); ongoingtouches.splice(idx, 1); // remove it; we're done } } since the idea is to immediately abort the touch, we simply remove it from the ongoing touch list without drawing a final line segment. convenience functions this example uses two convenience functions that should be looked at briefly to help make the rest of the code more clear. selecting a color for each touch to make each touch's drawing look different, the colorfortouch() function is used to pick a color based on the touch's unique identifier. this identifier is an opaque number, but we can at least rely on it differing between the currently-active touches. function colorfortouch(touch) { var r = touch.identifier % 16; var g = math.floor(touch.identifier / 3) ...
USBDevice - Web APIs
Web › API › USBDevice
only one of three properties that declare the usb protocol version supported by the device. the other two properties are usbdevice.usbversionmajor and usbdevice.usbversionminor. usbdevice.vendorid read only the official usg.org-assigned vendor id. methods usbdevice.claiminterface() returns a promise that resolves when the requested interface is claimed for exclusive access. usbdevice.clearhalt() returns a promise that resolves when a halt condition is cleared. usbdevice.controltransferin() returns a promise that resolves with a usbtransferinresult when a command or status operation has been transmitted to the usb device. usbdevice.controltransferout() returns a promise that resolves with a usbtransferoutresult when a command or status operation has been transmitted from the us...
USBInTransferResult - Web APIs
es usbintransferresult.dataread only returns a dataview object containing the data 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. ...
USBIsochronousInTransferPacket - Web APIs
returns a dataview object containing the data received from the usb device in this packet, if any. usbisochronousintransferpacket.statusread only read 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 an isochronous endpoint does not need to be cleared. "babble" - the device responded with more data than was expected. specifications specification status comment webusbthe definition of 'usbisochronousintransferpacket' in that specification. draft initial definition. ...
USBIsochronousOutTransferPacket - Web APIs
ansferpacket.byteswrittenread only returns the number of bytes from the packet that were sent to the device. usbisochronousouttransferpacket.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 an isochronous endpoint does not need to be cleared. specifications specification status comment webusbthe definition of 'usbisochronousouttransferpacket' in that specification. draft initial definition. ...
USBOutTransferResult - Web APIs
usbouttransferresult.byteswrittenread 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. ...
Visual Viewport API - Web APIs
occur to the window's viewport. example the code below is based on the sample the specification, though it adds a few things that make it function better. it shows a function called viewporthandler(). when called it queries the offsetleft and height properties for values it uses in a css translate() method. you invoke this function by passing it to both event calls. one thing that may not be clear in this example is the use of the pendingupdate flag 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 (pend...
WebGL2RenderingContext - Web APIs
tances of the range of elements. webgl2renderingcontext.drawelementsinstanced() renders primitives from array data. in addition, it can execute multiple instances of a set of elements. webgl2renderingcontext.drawrangeelements() renders primitives from array data in a given range. webgl2renderingcontext.drawbuffers() specifies a list of color buffers to be drawn into. webgl2renderingcontext.clearbuffer[fiuv]() clears buffers from the currently bound framebuffer. query objects methods for working with webglquery objects. webgl2renderingcontext.createquery() creates a new webglquery object. webgl2renderingcontext.deletequery() deletes a given webglquery object. webgl2renderingcontext.isquery() returns true if a given object is a valid webglquery object. webgl2renderingcontext.b...
WebGLRenderingContext.bindFramebuffer() - Web APIs
fer); parameters target a glenum specifying the binding point (target). possible values: gl.framebuffer: collection buffer data storage of color, alpha, depth and stencil buffers used to render an image. when using a webgl 2 context, the following values are available additionally: gl.draw_framebuffer: equivalent to gl.framebuffer. used as a destination for drawing, rendering, clearing, and writing operations. gl.read_framebuffer: used as a source for reading operations. framebuffer a webglframebuffer object to bind. return value none. exceptions a gl.invalid_enum error is thrown if target is not gl.framebuffer, gl.draw_framebuffer, or gl.read_framebuffer. examples binding a frame buffer var canvas = document.getelementbyid('canvas'); var gl = canvas...
WebGLRenderingContext.checkFramebufferStatus() - Web APIs
get); parameters target a glenum specifying the binding point (target). possible values: gl.framebuffer: collection buffer data storage of color, alpha, depth and stencil buffers used to render an image. when using a webgl 2 context, the following values are available additionally: gl.draw_framebuffer: equivalent to gl.framebuffer. used as a destination for drawing, rendering, clearing, and writing operations. gl.read_framebuffer: used as a source for reading operations. return value a glenum indicating the completeness status of the framebuffer or 0 if an error occurs. possible enum return values: gl.framebuffer_complete: the framebuffer is ready to display. gl.framebuffer_incomplete_attachment: the attachment types are mismatched or not all framebuffe...
WebGLRenderingContext.disable() - Web APIs
encil 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 'disable' in that specification. recommendation initial definition for webgl. ...
WebGLRenderingContext.enable() - Web APIs
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 'enable' in that specification. recommendation initial definition for webgl. ...
WebGLRenderingContext.framebufferRenderbuffer() - Web APIs
target a glenum specifying the binding point (target) for the framebuffer. possible values: gl.framebuffer: collection buffer data storage of color, alpha, depth and stencil buffers used to render an image. when using a webgl 2 context, the following values are available additionally: gl.draw_framebuffer: equivalent to gl.framebuffer. used as a destination for drawing, rendering, clearing, and writing operations. gl.read_framebuffer: used as a source for reading operations. attachment a glenum specifying the attachment point for the render buffer. possible values: gl.color_attachment0: color buffer. gl.depth_attachment: depth buffer. gl.depth_stencil_attachment: depth and stencil buffer. gl.stencil_attachment: stencil buffer. when using a webgl 2 co...
WebGLRenderingContext.framebufferTexture2D() - Web APIs
vel); parameters target a glenum specifying the binding point (target). possible values: gl.framebuffer: collection buffer data storage of color, alpha, depth and stencil buffers used to render an image. when using a webgl 2 context, the following values are available additionally: gl.draw_framebuffer: equivalent to gl.framebuffer. used as a destination for drawing, rendering, clearing, and writing operations. gl.read_framebuffer: used as a source for reading operations. attachment a glenum specifying the attachment point for the texture. possible values: gl.color_attachment0: attaches the texture to the framebuffer's color buffer. gl.depth_attachment: attaches the texture to the framebuffer's depth buffer. gl.stencil_attachment: att...
WebGLRenderingContext.getFramebufferAttachmentParameter() - Web APIs
ame); parameters target a glenum specifying the binding point (target). possible values: gl.framebuffer: collection buffer data storage of color, alpha, depth and stencil buffers used to render an image. when using a webgl 2 context, the following values are available additionally: gl.draw_framebuffer: equivalent to gl.framebuffer. used as a destination for drawing, rendering, clearing, and writing operations. gl.read_framebuffer: used as a source for reading operations. attachment a glenum specifying the attachment point for the texture. possible values: gl.color_attachment0: texture attachment for the framebuffer's color buffer. gl.depth_attachment: texture attachment for the framebuffer's depth buffer. gl.stencil_attachment: texture attachment for...
WebGLRenderingContext.isEnabled() - Web APIs
encil_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: gl.enable(gl.stencil_test); gl.disable(gl.stencil_test); specifications ...
WebGLRenderingContext.makeXRCompatible() - Web APIs
requesting immersive-vr mode by checking to see if the button has the use-webxr class on it. if the button clicked by the user has that class (and we've confirmed that webxr is available by ensuring that the navigator.xr property exists), we use requestsession() to request a new webxr session and set the usingxr flag to true. if the other button was clicked, we ensure that xrsession is null and clear usingxr to false. then the startgame() function is called to trigger the beginning of gameplay. handlers are provided for both webglcontextlost and webglcontextrestored; in the first case, we make sure we're aware that the state can be recovered, while in the latter we actually reload the scene to ensure we have the correct resources for the current screen or headset configuration. specificati...
WebGLRenderingContext.scissor() - Web APIs
urn value none. exceptions if either width or height is a negative value, a gl.invalid_value error is thrown. examples when the scissor test is enabled, only pixels within the scissor box can be modified by drawing commands. // turn on scissor test gl.enable(gl.scissor_test); // set the scissor rectangle gl.scissor(x, y, width, height); // execute drawing commands in the scissor box (e.g. clear) // turn off scissor test again gl.disable(gl.scissor_test); to get the current scissor box dimensions, query the scissor_box constant which returns an int32array. gl.scissor(0, 0, 200, 200); gl.getparameter(gl.scissor_box); // int32array[0, 0, 200, 200] specifications specification status comment webgl 1.0the definition of 'scissor' in that specification. recomme...
Lighting in WebGL - Web APIs
it just runs two functions you supply — a vertex shader and a fragment shader — and expects you to write creative functions to get the results you want. in other words, if you want lighting you have to calculate it yourself. fortunately, it's not all that hard to do, and this article will cover some of the basics. this example uses the glmatrix library to perform its matrix and vertex math. you'll need to include it if you create your own project based on this code. our sample loads a copy from a cdn in our html's <head>. ...
WebGL tutorial - Web APIs
code written in javascript and special effects code (shader code) that is executed on a computer's graphics processing unit (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...
WebGL types - Web APIs
Web › API › WebGL API › Types
es are used in webgl interfaces. webgl 1 these types are used within a webglrenderingcontext. type web idl type description glenum unsigned long used for enums. see also the list of constants. glboolean boolean a boolean. glbitfield unsigned long a bit field that stores multiple, logical bits. used for example in webglrenderingcontext.clear(). glbyte byte 8-bit twos complement signed integer. glshort short 16-bit twos complement signed integer. glint long 32-bit twos complement signed integer. glsizei long used for sizes (e.g. width and height of the drawing buffer). glintptr long long special type for pointer arithmetic. glsizeiptr long long s...
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 of the polite peer, which always rolls itself back if it receives an offer while itself waiting for an answer to...
Writing WebSocket servers - Web APIs
onse. the first peer then closes the connection. any further data received after closing of connection is then discarded. miscellaneous websocket codes, extensions, subprotocols, etc. are registered at the iana websocket protocol registry. websocket extensions and subprotocols are negotiated via headers during the handshake. sometimes extensions and subprotocols very similar, but there is a clear distinction. extensions control the websocket frame and modify the payload, while subprotocols structure the websocket payload and never modify anything. extensions are optional and generalized (like compression); subprotocols are mandatory and localized (like ones for chat and for mmorpg games). extensions this section needs expansion. please edit if you are equipped to do so. think of an e...
Lighting a WebXR setting - Web APIs
he context of the proposed api, is out of scope for the moment. once the api has stabilized, we'll update this documentation with the details. security and privacy concerns there are a number of potential security issues involved with collecting all of this data in order to generate and apply lighting to your virtual objects using real-world data. of course, many ar applications make it pretty clear where the user is located. if the user is running an app called touring the louvre, there's a very good chance the user is located in the musée du louvre in paris, france. but browsers are required to take a number of steps to make it difficult to physically locate the user without their consent. ambient light sensor api the collection of light data using the ambient light sensor api introduce...
Advanced techniques: Creating and sequencing audio - Web APIs
...
Example and tutorial: Simple synth keyboard - Web APIs
t && dataset["pressed"]) { osclist[dataset["octave"][dataset["note"]]].stop(); osclist[dataset["octave"][dataset["note"]]] = null; delete dataset["pressed"]; } } notereleased() uses the data-octave and data-note custom attributes to look up the key's oscillator, then calls the oscillator's inherited stop() method to stop playing the note. finally, the osclist entry for the note is cleared and the data-pressed attribute is removed from the key element (as identified by event.target), to indicate that the note is not currently playing. changing the master volume the volume slider in the settings bar provides a simple interface to change the gain value on the master gain node, thereby changing the loudness of all playing notes. the changevolume() method is the handler for the cha...
Using the Web Storage API - Web APIs
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 argument — the key of the data item you want to remove — and removes it from the storage object for that domain. storage.clear() takes no arguments, and simply empties the entire storage object for that domain. specifications specification status comment html living standard living standard ...
Web Storage API - Web APIs
n, including page reloads and restores) stores data only for a session, meaning that the data is stored until the browser (or tab) is closed. data is never transferred to the server. storage limit is larger than a cookie (at most 5mb). localstorage does the same thing, but persists even when the browser is closed and reopened. stores data with no expiration date, and gets cleared only through javascript, or clearing the browser cache / locally stored data. storage limit is the maximum amongst the three. these mechanisms are available via the window.sessionstorage and window.localstorage properties (to be more precise, in supporting browsers the window object implements the windowlocalstorage and windowsessionstorage objects, which the localstorage and sessions...
Functions and classes available to Web Workers - Web APIs
icated workers shared workers service workers chrome workers outside workers atob() yes, on workerglobalscope yes, on workerglobalscope yes, on workerglobalscope yes, on workerglobalscope yes, on window btoa() yes, on workerglobalscope yes, on workerglobalscope yes, on workerglobalscope yes, on workerglobalscope yes, on window clearinterval() yes, on workerglobalscope yes, on workerglobalscope yes, on workerglobalscope yes, on workerglobalscope yes, on window cleartimeout() yes, on workerglobalscope yes, on workerglobalscope yes, on workerglobalscope yes, on workerglobalscope yes, on window dump() yes, on workerglobalscope yes, on workerglobalscope yes, on workerglob...
Using Web Workers - Web APIs
ast performance improvement when sending large data sets. think of it as pass-by-reference if you're from the c/c++ world. however, unlike pass-by-reference, the 'version' from the calling context is no longer available once transferred. its ownership is transferred to the new context. for example, when transferring an arraybuffer from your main app to a worker script, the original arraybuffer is cleared and no longer usable. its content is (quite literally) transferred to the worker context. // create a 32mb "file" and fill it. var uint8array = new uint8array(1024 * 1024 * 32); // 32mb for (var i = 0; i < uint8array.length; ++i) { uint8array[i] = i; } worker.postmessage(uint8array.buffer, [uint8array.buffer]); note: for more information on transferable objects, performance, and feature-...
Window.history - Web APIs
Web › API › Window › history
ck(); notes for top-level pages you can see the list of pages in the session history, accessible via the history object, in the browser's dropdowns next to the back and forward buttons. for security reasons the history object doesn't allow the non-privileged code to access the urls of other pages in the session history, but it does allow it to navigate the session history. there is no way to clear the session history or to disable the back/forward navigation from unprivileged code. the closest available solution is the location.replace() method, which replaces the current item of the session history with the provided url. specifications specification status comment html living standardthe definition of 'the history interface' in that specification. living stand...
Window.onpaint - Web APIs
Web › API › Window › onpaint
w.onpaint = funcref; funcref is a handler function. notes onpaint doesn't work currently, and it is questionable whether this event is going to work at all, see bug 239074. the paint event is raised when the window is rendered. this event occurs after the load event for a window, and reoccurs each time the window needs to be re-rendered, such as when another window obscures it and is then cleared away. specification this is not part of any specification. ...
Window.prompt() - Web APIs
Web › API › Window › prompt
12firefox full support 1ie full support 4notes full support 4notes notes this function has no effect in the modern ui/metro version of internet explorer for windows 8. it does not display a prompt to the user, and always returns undefined. it is not clear whether this is a bug or intended behavior. desktop versions of ie do implement this function.opera full support 3notes full support 3notes notes starting with opera 33, this method is blocked inside an <iframe> unless its sandbox attribute has the value allow-modals.safari full support ...
Window.sessionStorage - Web APIs
the read-only sessionstorage property accesses a session storage object for the current origin. sessionstorage is similar to localstorage; the difference is that while data in localstorage doesn't expire, data in sessionstorage is cleared when the page session ends. a page session lasts as long as the browser is open, and survives over page reloads and restores. opening a page in a new tab or window creates a new session with the value of the top-level browsing context, which differs from how session cookies work. opening multiple tabs/windows with the same url creates sessionstorage for each tab/window. closing a tab/window ends the session and clears objects in sessionstorage. data stored in sessionstorage is specific to the protocol of the page. in particular, data stored by a scrip...
Window.setImmediate() - Web APIs
es. this method is not expected to become standard, and is only implemented by recent builds of internet explorer and node.js 0.10+. it meets resistance both from gecko (firefox) and webkit (google/apple). syntax var immediateid = setimmediate(func, [param1, param2, ...]); var immediateid = setimmediate(func); where immediateid is the id of the immediate which can be used later with window.clearimmediate. func is the function you wish to call. all parameters will be passed directly to your function. notes the clearimmediate method can be used to clear the immediate actions, just like cleartimeout for settimeout. this method can be used instead of the settimeout(fn, 0) method to execute heavy operations. the feature can be emulated in a few different ways: postmessage can be us...
Window.updateCommands() - Web APIs
summary updates the state of commands of the current chrome window (ui). syntax window.updatecommands("scommandname") parameters scommandname is a particular string which describes what kind of update event this is (e.g. whether we are in bold right now). notes this enables or disables items (setting or clearing the "disabled" attribute on the command node as appropriate), or ensures that the command state reflects the state of the selection by setting current state information in the "state" attribute of the xul command nodes. specification dom level 0. not part of specification. browser compatibility the compatibility table in this page is generated from structured data. if you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and ...
WindowOrWorkerGlobalScope - Web APIs
l scope, serialized as a string. methods these methods are defined on the windoworworkerglobalscope mixin, and implemented by window and workerglobalscope. windoworworkerglobalscope.atob() decodes a string of data which has been encoded using base-64 encoding. windoworworkerglobalscope.btoa() creates a base-64 encoded ascii string from a string of binary data. windoworworkerglobalscope.clearinterval() cancels the repeated execution set using windoworworkerglobalscope.setinterval(). windoworworkerglobalscope.cleartimeout() cancels the delayed execution set using windoworworkerglobalscope.settimeout(). windoworworkerglobalscope.createimagebitmap() accepts a variety of different image sources, and returns a promise which resolves to an imagebitmap. optionally the source is cropped ...
WorkerGlobalScope - Web APIs
ws you to write a message to stdout — i.e. in your terminal. this is the same as firefox's window.dump, but for workers. methods implemented from elsewhere windoworworkerglobalscope.atob() decodes a string of data which has been encoded using base-64 encoding. windoworworkerglobalscope.btoa() creates a base-64 encoded ascii string from a string of binary data. windoworworkerglobalscope.clearinterval() cancels the repeated execution set using windoworworkerglobalscope.setinterval(). windoworworkerglobalscope.cleartimeout() cancels the delayed execution set using windoworworkerglobalscope.settimeout(). windoworworkerglobalscope.createimagebitmap() accepts a variety of different image sources, and returns a promise which resolves to an imagebitmap. optionally the source is cropped ...
XRSession.onsqueeze - Web APIs
a snippet of code, but should establish the general idea. after checking that the event occurred on the user's dominant hand, the pose's target ray is obtained. then we pass the currently held object and the target ray's transform matrix into a function we call dropobjectusingray() to drop the object, using the target ray to determine the surface upon which the object should be placed. this also clears the value of heldobject so we know that there's no longer an object in hand. xrsession.onsqueeze = event => { if (event.inputsource.handedness == user.handedness) { let targetraypose = event.frame.getpose(event.inputsource.targetrayspace, myrefspace); if (user.heldobject && targetraypose) { dropobjectusingray(user.heldobject, targetraypose.transform.matrix): } } }; see ...
XRSession.onsqueezeend - Web APIs
t.frame.getpose(event.inputsource.targetrayspace, myrefspace; if (user.heldobject) { cancelobjectdrag(user.heldobject); } } }; this code presumes that if the user actually intentionally completed the drag, user.heldobject will be null here. that's because (in this example, at least) the handler for the squeeze event has already dropped the object into its new location and then cleared the value of heldobject to indicate that the user is no longer holding anything. specifications specification status comment webxr device apithe definition of 'xrsession.onsqueezeend' in that specification. working draft initial definition. ...
XSLTProcessor - Web APIs
. a null value for namespaceuri is treated the same as an empty string. [throws] void xsltprocessor.removeparameter(string namespaceuri, string localname) removes the parameter if it was previously set. this will make the xsltprocessor use the default value for the parameter as specified in the stylesheet. a null value for namespaceuri is treated the same as an empty string. void xsltprocessor.clearparameters() removes all set parameters from the xsltprocessor. the xsltprocessor will then use the defaults specified in the xslt stylesheet. void xsltprocessor.reset() removes all parameters and stylesheets from the xsltprocessor. properties non-web-exposed properties the following properties are [chromeonly] and not exposed to web content: [chromeonly] attribute unsigned long xsltproc...
mssitemodejumplistitemremoved - Web APIs
parameters pevtobj [in] type: ihtmleventobj pointer to an ihtmleventobj interface for the current event. see also microsoft api extensions ...
msthumbnailclick - Web APIs
ihtmleventobj interface for the current event. ...
ARIA live regions - Accessibility
the first time the function executes, the entirety of the string that is added will be announced. on subsequent calls, only the parts of the content that changed compared to the previous content will be announced. for instance, when the clock changes from "17:33" to "17:34", assistive technologies will only announce "4", which won't be very useful to users. one way around this would be to first clear the contents of the live region, and then inject the new content. however, this can sometimes be unreliable, as it's dependent on the exact timing of these two updates. aria-atomic="true" ensures that each time the live region is updated, the entirety of the content is announced in full (e.g. "time: 17:34"). <div id="clock" role="timer" aria-live="polite" aria-atomic="true"></div> note: as o...
ARIA: timer role - Accessibility
the first time the function executes, the entirety of the string that is added will be announced. on subsequent calls, only the parts of the content that changed compared to the previous content will be announced. for instance, when the clock changes from "17:33" to "17:34", assistive technologies will only announce "4", which won't be very useful to users. one way around this would be to first clear the contents of the live region, and then inject the new content. however, this can sometimes be unreliable, as it's dependent on the exact timing of these two updates. aria-atomic="true" ensures that each time the live region is updated, the entirety of the content is announced in full (e.g. "time: 17:34"). <div id="clock" role="timer" aria-live="polite" aria-atomic="true"></div> accessibilit...
ARIA: button role - Accessibility
// don't add blank entries to the list. if(name.length > 0) { listitem = document.createelement('li'); listitem.appendchild(document.createtextnode(name)); // add the new name to the list. let list = document.getelementbyid('namelist'); l...
ARIA: listbox role - Accessibility
o that label. aria-labelledby identifies the visible element or elements in a space-separated list of element ids which identify the listbox. if there's no visible label, then aria-label should be used instead to include a label. (note: "labelled", with two l's, is the correct spelling based on the accessibility api conventions.) aria-roledescription a human-readable string value which more 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". (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 th...
Accessibility Information for Web Authors - Accessibility
n webpage related to section 508 standards and/or the wcag guidelines. it can perform a "complete webpage quality check" for accessibility, privacy, searchability, metadata and even alt text attribute quality. the web author chooses the guidelines (as a basis for errors and warnings) to be used by "cynthia says™": section 508, wcag priorities 1, 2 and 3. the output data report is displayed in a clear and well structured table where each and all checkpoints are identified and described (along with an helpful clickable link to the related reference guideline) into logical groups and according to measurable results: passed, warning, failed for automated verification, warning for manual verification, not selected, not available, not related, etc. accessibility valet from webthing description...
Web accessibility for seizures and physical reactions - Accessibility
, one of epilepsy's most complex conditions" talks about static images and patterns. "static or moving patterns of discernable light and dark stripes have the same effect as flashing lights because of the alternation of dark and bright areas." the epilepsy foundation of america working group is able to "quantify" the problem a little. "a pattern with the potential for provoking seizures contains clearly discernible stripes, numbering more than five light-dark pairs of stripes in any orientation" in addition to stripes, checkered patterns have also been known to cause photosensitive seizures, according to cedars-sinai. although static images are possible as triggers, they are less consistent. the trigger that is well established and strong is flashing/strobe lights. dr. selim benbadis of usf's...
Web Accessibility: Understanding Colors and Luminance - Accessibility
this is a significant consideration. note that in that same section of the css color module 3, there are algorigthms available to translate the hsl to rgb. newer technologies, such as opengl and direct3d incorporate support for the srgb gamma curve, although some articles for opengl reference use of rgba rather than srgb. webgl is usually in the rgba format; see an example of how it is used in "clearing with colors". where accessibility is concerned, however, standards and guidelines are currently written predominantly using the srgb color space, especially as it applies to color contrast ratios. in speaking specifically to relative luminance, wcag's definition of relative luminance notes: "note 2: almost all systems used today to view web content assume srgb encoding. unless it is known...
Operable - Accessibility
ed links, etc. the only exception to this is where a page is one step in a process, so should only logically have links to the previous and next steps. most of these mechanisms can be created using simple html features, for example see search field, creating a navigation menu, styling links as buttons. 2.4.6 headings and labels (aa) heading (e.g. <h2>) and <label> elements clearly describe the purpose of the content and form elements they are supposed to be describing. see ui controls, meaningful text labels, the basics of headings and paragraphs, the <label> element. note that you should avoid duplicating headings or labels (e.g. multiple instances of "further information"), unless the structure allows you to differentiate between them easily. ...
Text labels and names - Accessibility
epias verticillata</figcaption> </figure> fieldset elements must be labeled fieldset elements must have a text description, similar to other form elements. use the <legend> element to describe the purpose of a fieldset. use a legend to label a fieldset when grouping a set of form elements together with a <fieldset> element, you should include a nested <legend> element inside it, containing a clear description of the group. users of assistive technology find this description helpful when trying to work out the overall purpose of the group. without the legend, they would have to navigate around the individual form controls in the group to infer an idea of the overall purpose, which could result in confusion. examples <form> <fieldset> <legend>choose your favorite monster</legend> ...
::-webkit-search-cancel-button - CSS: Cascading Style Sheets
the ::-webkit-search-cancel-button css pseudo-element represents a button (the "cancel button") at the edge of an <input> of type="search" which clears away the current value of the <input> element. this button and pseudo-element are non-standard, supported only in webkit and blink, hence the vendor prefix. the clear button is only shown on non-empty search <input> elements. syntax selector::-webkit-search-cancel-button specifications not part of any standard. ...
:host-context() - CSS: Cascading Style Sheets
color: gray; }' + ':host(.footer) { color : red; }' + ':host { background: rgba(0,0,0,0.1); padding: 2px 5px; }'; the :host-context(h1) { font-style: italic; } and :host-context(h1):after { content: " - no links in headers!" } rules style the instance of the <context-span> element (the shadow host in this instance) inside the <h1>. we've used it to make it clear that the custom element shouldn't appear inside the <h1> in our design. specifications specification status comment css scoping module level 1the definition of ':host-context()' in that specification. working draft initial definition. browser compatibility the compatibility table on this page is generated from structured data. if you'd like to contribut...
:link - CSS: Cascading Style Sheets
Web › CSS › :link
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. (after that, you'll need to clear your browser history to see them again.) however, the background-color values are likely to remain, as most browsers do not set that property on visited links by default. html <a href="#ordinary-target">this is an ordinary link.</a><br> <a href="">you've already visited this link.</a><br> <a>placeholder link (won't get styled)</a> css a:link { background-color: gold; color: green; } re...
font-style - CSS: Cascading Style Sheets
ollowing result: @font-face { font-family: garamond; src: url('garamond.ttf'); } the italicized version of this text uses the same glyphs present in the unstyled version, but they are artificially sloped by a few degrees. on the other hand, if a true italicized version of the font family exists, we can include it in the src descriptor and specify the font style as italic, so that it is clear that the font is italicized. true italics use different glyphs and are a bit different from their upright counterparts, having some unique features and generally have a rounded and calligraphic quality. these fonts are specially created by font designers and are not artificially sloped. @font-face { font-family: garamond; src: url('garamond-italic.ttf'); font-style: italic; } specificat...
CSS Animations tips and tricks - CSS: Cascading Style Sheets
state. if instead you'd like the animation to complete and then come to a stop you have to try a different approach. the main tricks are: make your animation as self-contained as possible. this means you should not rely on animation-direction: alternate. instead you should explicitly write a keyframe animation that goes through the full animation in one forward repetition. use javascript and clear the animation being used when the animationiteration event fires. the following demo shows how you'd achieve the aforementioned javascript technique: .slidein { animation-duration: 5s; animation-name: slidein; animation-iteration-count: infinite; } .stopped { animation-name: none; } @keyframes slidein { 0% { margin-left: 0%; } 50% { margin-left: 50%; } 100% { ma...
Border-image generator - CSS: Cascading Style Sheets
%; } .span_10 { width: 83%; } .span_9 { width: 74.54%; } .span_8 { width: 66.08%; } .span_7 { width: 57.62%; } .span_6 { width: 49.16%; } .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 * =========================================================================...
Border-radius generator - CSS: Cascading Style Sheets
} .span_10 { width: 83%; } .span_9 { width: 74.54%; } .span_8 { width: 66.08%; } .span_7 { width: 57.62%; } .span_6 { width: 49.16%; } .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 * =========================================================================...
Box-shadow generator - CSS: Cascading Style Sheets
%; } .span_10 { width: 83%; } .span_9 { width: 74.54%; } .span_8 { width: 66.08%; } .span_7 { width: 57.62%; } .span_6 { width: 49.16%; } .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 * =========================================================================...
Introduction to the CSS basic box model - CSS: Cascading Style Sheets
he margin area, bounded by the margin edge, extends the border area to include an empty area used to separate the element from its neighbors. its dimensions are the margin-box width and the margin-box height. the size of the margin area is determined by the margin-top, margin-right, margin-bottom, margin-left, and shorthand margin properties. when margin collapsing occurs, the margin area is not clearly defined since margins are shared between boxes. finally, note that for non-replaced inline elements, the amount of space taken up (the contribution to the height of the line) is determined by the line-height property, even though the borders and padding are still displayed around the content. ...
Backwards Compatibility of Flexbox - CSS: Cascading Style Sheets
useful fallback techniques given that flexbox usage is initiated with value of the display property, when needing to support very old browsers which do not support flexbox at all, fallbacks can be created by overwriting one layout method with another. the specification defines what happens if you use other layout methods on an element which then becomes a flex item. floated items “float and clear do not create floating or clearance of flex item, and do not take it out-of-flow.” - 3. flex containers in the following live example, i have floated two blocks and then set display: flex on the container. the items are now flex items, which means they stretch to equal height. any float behaviour does not apply. you can test the fallback behaviour by removing display: flex from the wrapper. ...
Block and inline layout in normal flow - CSS: Cascading Style Sheets
splay model level 3, we can learn more about how the display property changes the behaviour of boxes and the boxes they generate. the display type of an element defines the outer display type; this dictates how the box displays alongside other elements in the same formatting context. it also defines the inner display type, which dictates how boxes inside this element behave. we can see this very clearly when considering a flex layout. in the example below i have a <div>, which i have given display: flex. the flex container behaves like a block element: it displays on a new line and takes up all of the space it can in the inline direction. this is the outer display type of block. the flex items however are participating in a flex formatting context, because their parent is the element with dis...
Flow Layout and Overflow - CSS: Cascading Style Sheets
ould enable the adding of an ellipsis when text overflows in the block dimension. this is useful in the situation where you have a listing of articles, for example, and you display the listings in fixed height boxes which only take a limited amount of text. it may not be obvious to the reader that there is more content to click through to when clicking the box or the title. an ellipsis indicates clearly the fact there is more content. the specification would allow a string of content or a regular ellipsis to be inserted. summary whether you are in continuous media on the web or in a paged media format such as print or epub, understanding how content overflows is useful when dealing with any layout method. by understanding how overflow works in normal flow, you should find it easier to unders...
In Flow and Out of Flow - CSS: Cascading Style Sheets
ou are then able to use the offset values to push it around. the space that it would have been placed in normal flow is reserved however, as you can see in the example below. when you do anything to remove, or shift an item from where it would be placed in normal flow, you can expect to need to do some managing of the content and the content around it to prevent overlaps. whether that involves clearing floats, or ensuring that an element with position: absolute does not sit on top of some other content. for this reason methods which remove elements from being in-flow should be used with understanding of the effect that they have. summary in this guide we have covered the ways to take an element out of flow in order to achieve some very specific types of positioning. in the next guide we wi...
Introduction to formatting contexts - CSS: Cascading Style Sheets
r than visible elements with display: flow-root or display: flow-root list-item elements with contain: layout, content, or strict flex items grid items multicol containers elements with column-span set to all this is useful because a new bfc will behave much like the outermost document in that it becomes a mini-layout inside the main layout. a bfc contains everything inside it, float and clear only apply to items inside the same formatting context, and margins only collapse between elements in the same formatting context. bfc creation examples let's have a look at a couple of these in order to see the effect creating a new bfc. in the example below, we have a floated element inside a <div> with a border applied. the content of that <div> has floated alongside the floated element. as...
Layout using named grid lines - CSS: Cascading Style Sheets
ing items by the lines created by defining grid tracks and also how to place items using named template areas. in this guide we are going to look at how these two things work together when we use named lines. line naming is incredibly useful, but some of the more baffling looking grid syntax comes from this combination of names and track sizes. once you work through some examples it should become clearer and easier to work with. naming lines when defining a grid you can assign some or all of the lines in your grid a name when you define your grid with the grid-template-rows and grid-template-columns properties. to demonstrate i’ll use the simple layout created in the guide on line-based placement. this time i’ll create the grid using named lines. * {box-sizing: border-box;} .wrapper {...
Realizing common layouts using CSS Grid Layout - CSS: Cascading Style Sheets
ng the end line number, i have chosen to say how many tracks this element should span, using the span keyword. i like this approach as when working with a multiple-column layout system we usually think of blocks in terms of the number of tracks of the grid they span, and adjust that for different breakpoints. to see how the blocks align themselves to the tracks, use the firefox grid inspector. it clearly demonstrates how our items are placed. there are some key differences with how a grid layout works over the grid systems you may have used previously. as you can see, we do not need to add any markup to create a row, grid systems need to do this to stop elements popping up into the row above. with css grid layout, we can place things into rows, with no danger of them rising up into the row a...
CSS Logical Properties and Values - CSS: Cascading Style Sheets
-radius border-style (logical keyword) border-width (logical keyword) margin (logical keyword) margin-block margin-block-end margin-block-start margin-inline margin-inline-end margin-inline-start padding (logical keyword) padding-block padding-block-end padding-block-start padding-inline padding-inline-end padding-inline-start properties for floating and positioning clear (inline-end and inline-start keywords) float (inline-end and inline-start keywords) inset inset-block inset-block-end inset-block-start inset-inline inset-inline-end inset-inline-start other properties caption-side (inline-end and inline-start keywords) overflow-block overflow-inline overscroll-behavior-block overscroll-behavior-inline resize (block and inline keywords) text-...
CSS Positioned Layout - CSS: Cascading Style Sheets
css positioned layout is a module of css that defines how to position elements on the page. reference css properties bottom clear float left position right top z-index guides understanding css z-index presents the notion of stacking context and explains how z-ordering works, with several examples. specifications specification status comment css positioned layout module level 3 working draft css level 2 (revision 1) recommendation ...
CSS Properties Reference - CSS: Cascading Style Sheets
erright border-right-color borderrightcolor border-right-style borderrightstyle border-right-width borderrightwidth border-style borderstyle border-top bordertop border-top-color bordertopcolor border-top-style bordertopstyle border-top-width bordertopwidth border-width borderwidth clear clear clip clip color color cursor cursor display display filter filter float cssfloat font font font-family fontfamily font-size fontsize font-variant fontvariant font-weight fontweight height height left left letter-spacing le...
Introducing the CSS Cascade - CSS: Cascading Style Sheets
Web › CSS › Cascade
s of animations, theme changes, and so forth. the css property all lets you quickly set (almost) everything in css back to a known state. all lets you opt to immediately restore all properties to any of their initial (default) state, the state inherited from the previous level of the cascade, a specific origin (the user-agent stylesheet, the author stylesheet, or the user stylesheet), or even to clear the values of the properties entirely. css animations and the cascade css animations, using @keyframes at-rules, define animations between states. keyframes don't cascade, meaning that at any given time css takes values from only one single @keyframes, and never mixes multiple ones together. when several keyframes are appropriate, it chooses the latest defined in the most important document, b...
Microsoft CSS extensions - CSS: Cascading Style Sheets
ing -ms-scroll-limit -ms-scroll-limit-x-max -ms-scroll-limit-x-min -ms-scroll-limit-y-max -ms-scroll-limit-y-min -ms-scroll-rails -ms-scroll-snap-points-x -ms-scroll-snap-points-y -ms-scroll-snap-x -ms-scroll-snap-y -ms-scroll-translation -ms-text-autospace -ms-touch-select -ms-wrap-flow -ms-wrap-margin -ms-wrap-through zoom pseudo-elements ::-ms-browse ::-ms-check ::-ms-clear ::-ms-expand ::-ms-fill ::-ms-fill-lower ::-ms-fill-upper ::-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 ...
CSS reference - CSS: Cascading Style Sheets
Web › CSS › Reference
idthborder-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-stylecounters()cross-fade()cubic-bezier()::cue::cue-regioncursor<custom-ident>d:defaultdeg<dimension>:dirdirection:disableddisplay<displa...
Linear-gradient Generator - CSS: Cascading Style Sheets
...
Universal selectors - CSS: Cascading Style Sheets
space ns *|* - matches all elements |* - matches all elements without any declared namespace syntax * { style properties } the asterisk is optional with simple selectors. for instance, *.warning and .warning are equivalent. examples css * [lang^=en] { color: green; } *.warning { color: red; } *#maincontent { border: 1px solid blue; } .floating { float: left } /* automatically clear the next sibling after a floating element */ .floating + * { clear: left; } html <p class="warning"> <span lang="en-us">a green span</span> in a red paragraph. </p> <p id="maincontent" lang="en-gb"> <span class="warning">a red span</span> in a green paragraph. </p> result specifications specification status comment selectors level 4the definition of 'univ...
Visual formatting model - CSS: Cascading Style Sheets
ext of their containing block or establish an independent formatting context. a grid container, for example, establishes a new grid formatting context for its children. independent formatting contexts contain floats, and margins do not collapse across formatting context boundaries. therefore, creating a new block formatting context can ensure that floats remain inside a box. developers sometimes clear floats by changing the value of the overflow property, as this creates a new block formatting context. the newer value of display: flow-root creates a new block formatting context in order to gain the useful effects of this, without any unwanted issues caused by changing the value of overflow. block boxes in specifications, block boxes, block-level boxes, and block containers are all referred t...
Adapting to the new two-value syntax of display - CSS: Cascading Style Sheets
ss familiar. the two-value display: block flow-root maps to a fairly recent single value; display: flow-root. this value's only purpose is to create a new block formatting context (bfc). a bfc ensures that everything inside your box stays inside it, and things from outside the box cannot intrude into it. the most obvious use-case for creating a new bfc is to contain floats, and avoid the need for clearfix hacks. in the example below we have a floated item inside a container. the float is contained by the bordered box, which wraps it and the text alongside. if you remove the line display: flow-root then the float will poke out of the bottom of the box. if you are using firefox you can replace it with the newer display: block flow-root, which will achieve the same as the single flow-root value. ...
font-variant-numeric - CSS: Cascading Style Sheets
below, space-separated, in any order. values normal this keyword leads to the deactivation of the use of such alternate glyphs. ordinal this keyword forces the use of special glyphs for the ordinal markers, like 1st, 2nd, 3rd, 4th in english or a 1a in italian. it corresponds to the opentype values ordn. slashed-zero this keyword forces the use of a 0 with a slash; this is useful when a clear distinction between o and 0 is needed. it corresponds to the opentype values zero. <numeric-figure-values> these values control the figures used for numbers. two values are possible: lining-nums activating the set of figures where numbers are all lying on the baseline. it corresponds to the opentype values lnum. oldstyle-nums activating the set of figures where some numbers, like 3, 4, 7,...
font - CSS: Cascading Style Sheets
Web › CSS › font
ext-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_style") + " " + getcheckedvalue("font_variant") + " " + get...
margin-bottom - CSS: Cascading Style Sheets
working draft no significant change css level 2 (revision 1)the definition of 'm...
opacity - CSS: Cascading Style Sheets
Web › CSS › opacity
here <alpha-value> = <number> | <percentage> examples setting background opacity html <div class="light">you can barely see this.</div> <div class="medium">this is easier to see.</div> <div class="heavy">this is very easy to see.</div> css div { background-color: yellow; } .light { opacity: 0.2; /* barely see the text over the background */ } .medium { opacity: 0.5; /* see the text more clearly over the background */ } .heavy { opacity: 0.9; /* see the text very clearly over the background */ } result setting opacity on hover html <img src="//developer.mozilla.org/static/img/opengraph-logo.png" alt="mdn logo" width="128" height="146" class="opacity"> css img.opacity { opacity: 1; filter: alpha(opacity=100); /* ie8 and lower */ zoom: 1; /* triggers "haslayout" in i...
Audio and Video Delivery - Developer guides
ow javascript to generate media streams for playback. allowing javascript to generate streams facilitates a variety of use cases like adaptive streaming and time shifting live streams. encrypted media extensions (eme) encrypted media extensions is a w3c proposal to extend htmlmediaelement, providing apis to control playback of protected content. the api supports use cases ranging from simple clear key decryption to high value video (given an appropriate user agent implementation). license/key exchange is controlled by the application, facilitating the development of robust playback applications supporting a range of content decryption and protection technologies. one of the principle uses of eme is to allow browsers to implement drm (digital rights management), which helps to prevent we...
Using HTML sections and outlines - Developer guides
hey are intended to enhance the limited semantics of earlier versions of html, which included only the <div> tag as a generic mechanism for grouping related content. for example, <div class="navigation"> does not suggest any meaning about its content to a browser; only a human reading the html source can divine the meaning of a class like navigation. by contrast, the <nav> sectioning element more clearly describes to browsers and other devices the content contained: links or other navigational structures to help users move through and understand where they are in a site's or page's content. new semantic elements were added to html5 to improve and clarify the sectioning of websites into meaningful areas of content. it is important for developers to use these semantic elements in line with their...
<acronym> - HTML: Hypertext Markup Language
Web › HTML › Element › acronym
usage note: this element has been removed in html5 and shouldn't be used anymore. instead web developers should use the <abbr> element. attributes this element only has global attributes, which are common to all elements. dom interface this element implements the htmlelement interface. implementation note: up to gecko 1.9.2 inclusive, firefox implements the htmlspanelement interface for this element. ...
<applet>: The Embed Java Applet element - HTML: Hypertext Markup Language
Web › HTML › Element › applet
ripting language embedded in the document. name this attribute assigns a name to the applet so that it can be identified by other resources; particularly scripts. object this attribute specifies the url of a serialized representation of an applet. src as defined for internet explorer 4 and higher, this attribute specifies a url for an associated file for the applet. the meaning and use is unclear and not part of the html standard. vspace this attribute specifies additional vertical space, in pixels, to be reserved above and below the applet. width this attribute specifies in pixels the width that the applet needs. example html <applet code="game.class" align="left" archive="game.zip" height="250" width="350"> <param name="difficulty" value="easy"> <b>sorry, you need java to pl...
<bdi>: The Bidirectional Isolate element - HTML: Hypertext Markup Language
Web › HTML › Element › bdi
ext from affecting its surroundings. though the same visual effect can be achieved using the css rule unicode-bidi: isolate on a <span> or another text-formatting element, html authors should not use this approach because it is not semantic and browsers are allowed to ignore css styling. embedding the characters in <span dir="auto"> has the same effect as using <bdi>, but its semantics are less clear. content categories flow content, phrasing content, palpable content. permitted content phrasing content. tag omission none, both the starting and ending tag are mandatory. permitted parents any element that accepts phrasing content. implicit aria role no corresponding role permitted aria roles any dom interface ...
<br>: The Line Break element - HTML: Hypertext Markup Language
Web › HTML › Element › br
a <br> element is included at each point where we want the text to break. the text after the <br> begins again at the start of the next line of the text block. note: do not use <br> to create margins between paragraphs; wrap them in <p> elements and use the css margin property to control their size. attributes this element's attributes include the global attributes. deprecated attributes clear indicates where to begin the next line after the break. styling with css the <br> element has a single, well-defined purpose — to create a line break in a block of text. as such, it has no dimensions or visual output of its own, and there is very little you can do to style it. you can set a margin on <br> elements themselves to increase the spacing between the lines of text in the block, b...
<img>: The Image Embed element - HTML: Hypertext Markup Language
Web › HTML › Element › img
a separate page, so you can actually resize the content area. security and privacy concerns although <img> elements have innocent uses, they can have undesirable consequences for user security and privacy. see referer header: privacy and security concerns for more information and mitigations. accessibility concerns authoring meaningful alternate descriptions an alt attribute's value should clearly and concisely describe the image's content. it should not describe the presence of the image itself or the file name of the image. if the alt attribute is purposefully left off because the image has no textual equivalent, consider alternate methods to present what the image is trying to communicate. don't <img alt="image" src="penguin.jpg"> do <img alt="a rockhopper penguin standing on a b...
<input type="datetime-local"> - HTML: Hypertext Markup Language
ent may round to the nearest valid value, preferring numbers in the positive direction when there are two equally close options. for datetime-local inputs, the value of step is given in seconds, with a scaling factor of 1000 (since the underlying numeric value is in milliseconds). the default value of step is 60, indicating 60 seconds (or 1 minute, or 60,000 milliseconds). at this time, it's unclear what a value of any means for step when used with datetime-local inputs. this will be updated as soon as that information is determined. using datetime-local inputs date/time inputs sound convenient at first glance; they provide an easy ui for choosing dates and times, and they normalize the data format sent to the server, regardless of the user's locale. however, there are issues with <input t...
<link>: The External Resource Link element - HTML: Hypertext Markup Language
Web › HTML › Element › link
link> to establish a favicon for a site, and your site uses a content security policy (csp) to enhance its security, the policy applies to the favicon. if you encounter problems with the favicon not loading, verify that the content-security-policy header's img-src directive is not preventing access to it. the html and xhtml specifications define event handlers for the <link> element, but it is unclear how they would be used. under xhtml 1.0, empty elements such as <link> require a trailing slash: <link />. webtv supports the use of the value next for rel to preload the next page in a document series. attributes this element includes the global attributes. as this attribute is only used when rel="preload" or rel="prefetch" has been set on the <link> element. it specifies the type of co...
<pre>: The Preformatted Text element - HTML: Hypertext Markup Language
Web › HTML › Element › pre
nt is ignored and no visual effect results in its present; to achieve such an effect, use css white-space instead. example html <p>using css to change the font color is easy.</p> <pre> body { color: red; } </pre> result accessibility concerns it is important to provide an alternate description for any images or diagrams created using preformatted text. the alternate description should clearly and concisely describe the image or diagram's content. people experiencing low vision conditions and browsing with the aid of assistive technology such as a screen reader may not understand what the preformatted text characters are representing when they are read out in sequence. a combination of the <figure> and <figcaption> elements, supplemented by a combination of an id and the aria role ...
<table>: The Table element - HTML: Hypertext Markup Language
Web › HTML › Element › table
this helps people navigating with the aid of assistive technology such as a screen reader, people experiencing low vision conditions, and people with cognitive concerns. mdn adding a caption to your table with <caption> caption & summary • tables •...
HTML elements reference - HTML: Hypertext Markup Language
Web › HTML › Element
obsolete and deprecated elements warning: these are old html elements which are deprecated and should not be used. you should never use them in new projects, and should replace them in old projects as soon as you can. they are listed here for informational purposes only. element description <acronym> the html acronym element (<acronym>) allows authors to clearly indicate a sequence of characters that compose an acronym or abbreviation for a word. <applet> the obsolete html applet element (<applet>) embeds a java applet into the document; this element has been deprecated in favor of <object>. <basefont> the obsolete html base font element (<basefont>) sets a default font face, size, and color for the other elements which are ...
HTML documentation index - HTML: Hypertext Markup Language
Web › HTML › Index
ontent, html:phrasing content, reference, web, abbr, abbreviation, semantics the html abbreviation element (<abbr>) represents an abbreviation or acronym; the optional title attribute can provide an expansion or description for the abbreviation. 57 <acronym> element, html, html:flow content, obsolete, reference, web the html acronym element (<acronym>) allows authors to clearly indicate a sequence of characters that compose an acronym or abbreviation for a word. 58 <address>: the contact address element address, author, contact, contact information, element, email, email address, html, html sections, html:flow content, html:palpable content, reference, web the html <address> element indicates that the enclosed html provides contact information for...
Preloading content with rel="preload" - HTML: Hypertext Markup Language
<canvas></canvas> <script src="main.js" defer></script> </body> here we preload our css and javascript files so they will be available as soon as they are required for the rendering of the page later on. this example is trivial, as the browser probably discovers the <link rel="stylesheet"> and <script> elements in the same chunk of html as the preloads, but the benefits can be seen much more clearly the later resources are discovered and the larger they are. for example: resources that are pointed to from inside css, like fonts or images. resources that javascript can request, like json, imported scripts, or web workers. larger images and video files. preload has other advantages too. using as to specify the type of content to be preloaded allows the browser to: prioritize resour...
HTTP authentication - HTTP
e rfc 7486, section 3, http origin-bound authentication, digital-signature-based mutual see rfc 8120 aws4-hmac-sha256 see aws docs basic authentication scheme the "basic" http authentication scheme is defined in rfc 7617, which transmits credentials as user id/password pairs, encoded using base64. security of basic authentication as the user id and password are passed over the network as clear text (it is base64 encoded, but base64 is a reversible encoding), the basic authentication scheme is not secure. https/tls should be used with basic authentication. without these additional security enhancements, basic authentication should not be used to protect sensitive or valuable information. restricting access with apache and basic authentication to password-protect a directory on an apac...
Choosing between www and non-www URLs - HTTP
our website) and always sharing links (by email/social networks, etc.) to the same domain. no, you can have two. what is important is that you are coherent and consistent with which one is the official domain. this official domain is called the canonical name. all your absolute links should use it. but even so, you can still have the other domain working: http allows two techniques so that it is clear for your users, or search engines, which domain is the canonical one, while still allowing the non-canonical domain to work and provide the expected pages. so, choose one of your domains as your canonical one! there are two techniques below to allow the non-canonical domain to work still. techniques for canonical urls there are different ways to choose which website is canonical. using http ...
Basics of HTTP - HTTP
en www and non-www urls this article provides guidance on how to choose whether to use a www-prefixed domain or not, along with the consequences of that choice. flow of an http session this fundamental article describes a typical http session: what happens under the hood when you click on a link in your browser. http messages http messages transmitted during requests or responses have a very clear structure. this introductory article describes this structure, its purpose, and its possibilities. frame and message structure in http/2 http/2 encapsulates and represents http/1.x messages in a binary frame. this article explains the frame structure, its purpose, and the way it's encoded. connection management in http/1.x http/1.1 was the first version of http to support persistent connectio...
HTTP conditional requests - HTTP
...
Connection management in HTTP/1.x - HTTP
destination server (or any intermediate proxies). the http headers involved in defining the connection model, like connection and keep-alive, are hop-by-hop headers with their values able to be changed by intermediary nodes. a related topic is the concept of http connection upgrades, wherein 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 ...
Authorization - HTTP
4-hmac-sha256) <credentials> if the "basic" authentication scheme is used, the credentials are constructed like this: the username and the password are combined with a colon (aladdin:opensesame). the resulting string is base64 encoded (ywxhzgrpbjpvcgvuc2vzyw1l). note: base64 encoding does not mean encryption or hashing! this method is equally secure as sending the credentials in clear text (base64 is a reversible encoding). prefer to use https in conjunction with basic authentication. examples authorization: basic ywxhzgrpbjpvcgvuc2vzyw1l see also http authentication for examples on how to configure apache or nginx servers to password protect your site with http basic authentication. specifications specification title rfc 7235, section 4.2: ...
Index - HTTP
Web › HTTP › Headers › Index
ww-authenticate header. 19 cache-control general header, http, http header, reference the cache-control general-header field is used to specify directives for caching mechanisms in both requests and responses. caching directives are unidirectional, meaning that a given directive in a request is not implying that the same directive is to be given in the response. 20 clear-site-data http, http header, reference, header the clear-site-data header clears browsing data (cookies, storage, cache) associated with the requesting website. it allows web developers to have more control over the data stored locally by a browser for their origins. 21 connection http, headers, reference, web the connection general header controls whether or not th...
Proxy-Authorization - HTTP
s "basic". see also the iana registry of authentication schemes. <credentials> the credentials are constructed like this: the username and the password are combined with a colon (aladdin:opensesame). the resulting string is base64 encoded (ywxhzgrpbjpvcgvuc2vzyw1l). note: base64 encoding does not mean encryption or hashing! this method is equally secure as sending the credentials in clear text (base64 is a reversible encoding). prefer to use https in conjunction with basic authentication. examples proxy-authorization: basic ywxhzgrpbjpvcgvuc2vzyw1l specifications specification title rfc 7235, section 4.4: proxy-authorization http/1.1: authentication rfc 7617 the 'basic' http authentication scheme ...
SameSite cookies - HTTP
...
Vary - HTTP
Web › HTTP › Headers › Vary
response exactly like it would have been set on an equivalent 200 ok response. header type response header forbidden header name no syntax vary: * vary: <header-name>, <header-name>, ... directives * each request for a url is supposed to be treated as a unique and uncacheable request. a better way to indicate this is to use cache-control: no-store, which is clearer to read and also signals that the object shouldn't be stored ever. <header-name> a comma-separated list of header names to take into account when deciding whether or not a cached response can be used. examples dynamic serving when using the vary: user-agent header, caching servers should consider the user agent when deciding whether to serve the page from cache. for example, if you are se...
HTTP headers - HTTP
Web › HTTP › Headers
nt with a server. proxy-authenticate defines the authentication method that should be used to access a resource behind a proxy server. proxy-authorization contains the credentials to authenticate a user agent with a proxy server. caching age the time, in seconds, that the object has been in a proxy cache. cache-control directives for caching mechanisms in both requests and responses. clear-site-data clears browsing data (e.g. cookies, storage, cache) associated with the requesting website. expires the date/time after which the response is considered stale. pragma implementation-specific header that may have various effects anywhere along the request-response chain. used for backwards compatibility with http/1.0 caches where the cache-control header is not yet present. warning...
An overview of HTTP - HTTP
Web › HTTP › Overview
es the web page accordingly. a web page is a hypertext document. this means some parts of displayed text are links which can be activated (usually by a click of the mouse) to fetch a new web page, allowing the user to direct their user-agent and navigate through the web. the browser translates these directions in http requests, and further interprets the http responses to present the user with a clear response. the web server on the opposite side of the communication channel, is the server, which serves the document as requested by the client. a server appears as only a single machine virtually: this is because it may actually be a collection of servers, sharing the load (load balancing) or a complex piece of software interrogating other computers (like cache, a db server, or e-commerce serv...
205 Reset Content - HTTP
Web › HTTP › Status › 205
the http 205 reset content response status tells the client to reset the document view, so for example to clear the content of a form, reset a canvas state, or to refresh the ui. status 205 reset content specifications specification title rfc 7231, section 6.3.6: 205 reset content hypertext transfer protocol (http/1.1): semantics and content compatibility notes browser behavior differs if this response erroneously includes a body on persistent connections see 204 no content for more detail. ...
431 Request Header Fields Too Large - HTTP
Web › HTTP › Status › 431
request may be resubmitted after reducing the size of the request headers. 431 can be used when the total size of request headers is too large, or when a single header field is too large. to help those running into this error, indicate which of the two is the problem in the response body — ideally, also include which headers are too large. this lets users attempt to fix the problem, such as by clearing their cookies. servers will often produce this status if: the referer url is too long there are too many cookies sent in the request status 431 request header fields too large specifications specification title rfc 6585, section 5: 431 request header fields too large additional http status codes ...
Indexed collections - JavaScript
provide a mechanism for accessing raw binary data. as you already know, array objects grow and shrink dynamically and can have any javascript value. javascript engines perform optimizations so that these arrays are fast. however, as web applications become more and more powerful, adding features such as audio and video manipulation, access to raw data using websockets, and so forth, it has become clear that there are times when it would be helpful for javascript code to be able to quickly and easily manipulate raw binary data in typed arrays. buffers and views: typed array architecture to achieve maximum flexibility and efficiency, javascript typed arrays split the implementation into buffers and views. a buffer (implemented by the arraybuffer object) is an object representing a chunk of data...
Keyed collections - JavaScript
objects allow you to set keys to values, retrieve those values, delete keys, and detect whether something is stored at a key. map objects, however, have a few more advantages that make them better maps. the keys of an object are strings or symbols, where they can be of any value for...
Warning: unreachable code after return statement - JavaScript
rn statement, or when using a semicolon-less return statement but including an expression directly after. when an expression exists after a valid return statement, a warning is given to indicate that the code after the return statement is unreachable, meaning it can never be run. why should i have semicolons after return statements? in the case of semicolon-less return statements, it can be unclear whether the developer intended to return the statement on the following line, or to stop execution and return. the warning indicates that there is ambiguity in the way the return statement is written. warnings will not be shown for semicolon-less returns if these statements follow it: throw break var function examples invalid cases function f() { var x = 3; x += 4; return x; //...
JavaScript error reference - JavaScript
the pages below will provide additional details about these errors. each error is an object based upon the error object, and has a name and a message. errors displayed in the web console may include a link to the corresponding page below to help you quickly comprehend the problem in your code. for a beginner's introductory tutorial on fixing javascript errors, see what went wrong? troubleshooting javascript. ...
Array.from() - JavaScript
use as this when executing mapfn. return value a new array instance. description array.from() lets you create arrays from: array-like objects (objects with a length property and indexed elements); or iterable objects (objects such as map and set). array.from() has an optional parameter mapfn, which allows you to execute a map() function on each element of the array being created. more clearly, array.from(obj, mapfn, thisarg) has the same result as array.from(obj).map(mapfn, thisarg), except that it does not create an intermediate array. this is especially important for certain array subclasses, like typed arrays, since the intermediate array would necessarily have values truncated to fit into the appropriate type. the length property of the from() method is 1. in es2015, the clas...
Map - JavaScript
contacts.delete('raymond') // false contacts.delete('jessie') // true console.log(contacts.size) // 1 constructor map() creates a new map object. static properties get map[@@species] the constructor function that is used to create derived objects. instance properties map.prototype.size returns the number of key/value pairs in the map object. instance methods map.prototype.clear() removes all key-value pairs from the map object. map.prototype.delete(key) returns true if an element in the map object existed and has been removed, or false if the element does not exist. map.prototype.has(key) will return false afterwards. map.prototype.get(key) returns the value associated to the key, or undefined if there is none. map.prototype.has(key) returns a boolean asserting w...
NaN - JavaScript
the result is not a real number (e.g. math.sqrt(-1)) operand of an argument is nan (e.g. 7 ** nan) indeterminate form (e.g. 0 * infinity) any operation that involves a string and is not an addition operation (e.g. "foo"/3) examples testing against nan nan compares unequal (via ==, !=, ===, and !==) to any other value -- including to another nan value. use number.isnan() or isnan() to most clearly determine whether a value is nan. or perform a self-comparison: nan, and only nan, will compare unequal to itself. nan === nan; // false number.nan === nan; // false isnan(nan); // true isnan(number.nan); // true number.isnan(nan); // true function valueisnan(v) { return v !== v; } valueisnan(1); // false valueisnan(nan); // true valueisnan(number.nan); // tru...
Object.prototype.constructor - JavaScript
*/ } function createdconstructor() { /* ... */ } createdconstructor.prototype = object.create(parent.prototype) createdconstructor.prototype.constructor = createdconstructor // sets the correct constructor for future use createdconstructor.prototype.create = function create() { return new this.constructor() } new createdconstructor().create().create() // it's pretty fine ok, now it's pretty clear why changing the constructor can be useful. let's consider one more case. function parentwithstatic() {} parentwithstatic.startposition = { x: 0, y:0 } // static member property parentwithstatic.getstartposition = function getstartposition() { return this.startposition } function child(x, y) { this.position = { x: x, y: y } } child = object.assign(parentwithstatic) child.protot...
Object.create() - JavaScript
here too. but wait... as shown above, all seems normal so far. ...
Promise - JavaScript
fulfilled1, handlerejected1); const promisec = promisea.then(handlefulfilled2, handlerejected2); an action can be assigned to an already "settled" promise. in that case the action (if appropriate) will be performed at the first asynchronous opportunity. note that promises are guaranteed to be asynchronous. therefore, an action for an already "settled" promise will occur only after the stack has cleared and a clock-tick has passed. the effect is much like that of settimeout(action,10). const promisea = new promise( (resolutionfunc,rejectionfunc) => { resolutionfunc(777); }); // at this point, "promisea" is already settled. promisea.then( (val) => console.log("asynchronous logging has val:",val) ); console.log("immediate logging"); // produces output in this order: // immediate logging //...
Set - JavaScript
an, even though nan !== nan). constructor set() creates a new set object. static properties get set[@@species] the constructor function that is used to create derived objects. instance properties set.prototype.size returns the number of values in the set object. instance methods set.prototype.add(value) appends value to the set object. returns the set object. set.prototype.clear() removes all elements from the set object. set.prototype.delete(value) removes the element associated to the value and returns the value that set.prototype.has(value) would have previously returned. set.prototype.has(value) will return false afterwards. set.prototype.has(value) returns a boolean asserting whether an element is present with the given value in the set object or not. iterati...
Operator precedence - JavaScript
`a` first, then produce `a` if `a` is not `null` and not `undefined` a?.b.c; // evaluate `a` first, then produce `undefined` if `a` is `null` or `undefined` examples 3 > 2 && 2 > 1 // returns true 3 > 2 > 1 // returns false because 3 > 2 is true, then true is converted to 1 // in inequality operators, therefore true > 1 becomes 1 > 1, which // is false. adding parentheses makes things clear: (3 > 2) > 1. table the following table is ordered from highest (21) to lowest (1) precedence. precedence operator type associativity individual operators 21 grouping n/a ( … ) 20 member access left-to-right … . … computed member access left-to-right … [ … ] new (with argument list) n/a new … ( …...
if...else - JavaScript
y value that is not false, undefined, null, 0, -0, nan, or the empty string (""), and any object, including a boolean object whose value is false, is considered truthy when used as the condition. for example: var b = new boolean(false); if (b) // this condition is truthy examples using if...else if (cipher_char === from_char) { result = result + to_char; x++; } else { result = result + clear_char; } using else if note that there is no elseif syntax in javascript. however, you can write it with a space between else and if: if (x > 50) { /* do something */ } else if (x > 5) { /* do something */ } else { /* do something */ } assignment within the conditional expression it is advisable to not use simple assignments in a conditional expression, because the assignment can be co...
var - JavaScript
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 reason, it is recommended to always declare variables at the top of their scope (the top of global code and the top of function code) so it's clear which variables are function scoped (local) and which are resolved on the scope chain. it's important to point out that the hoisting will affect the variable declaration, but not its value's initialization. the value will be indeed assigned when the assignment statement is reached: function do_something() { console.log(bar); // undefined var bar = 111; console.log(bar); // 111 } // ...is...
JavaScript typed arrays - JavaScript
nd writing raw binary data in memory buffers. as you may already know, array objects grow and shrink dynamically and can have any javascript value. javascript engines perform optimizations so that these arrays are fast. however, as web applications become more and more powerful, adding features such as audio and video manipulation, access to raw data using websockets, and so forth, it has become clear that there are times when it would be helpful for javascript code to be able to quickly and easily manipulate raw binary data. this is where typed arrays come in. each entry in a javascript typed array is a raw binary value in one of a number of supported formats, from 8-bit integers to 64-bit floating-point numbers. however, typed arrays are not to be confused with normal arrays, as calling arr...
Recommended Web Performance Timings: How long is too long? - Web Performance
load goal the 'under a second' is often touted as optimal for load, but what does that mean? a second should be considered a rule in the maximum amount of time to indicate to a user that the request for new content was made and will load, such as the browser displaying the page title and the background color of the page displaying. the first asset retrieved from a request is usually an html document, which then makes calls for additional assets. ...
Introduction to progressive web apps - Progressive web apps (PWAs)
largest e-commerce site was rebuilt as a progressive web app in 2015, which resulted in 70% increase in conversions. the aliexpress pwa has also seen much better results than either the web or the native app, with a 104% increase in conversion rates for new users. given their profit increase, and the relatively low amount of work required for the conversion of these apps to pwas, the advantage is clear. early stage emerging startups like couponmoto have also started using progressive web apps to drive more consumer engagement, showing that they can help small as well as big companies to (re-)engage users more effectively. you can check the list at pwa.rocks for more examples. particularly worth mentioning is the hnpwa.com page—this lists an example implementation of the hacker news websit...
The building blocks of responsive design - Progressive web apps (PWAs)
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:nth-child(3) img { width: 20%; } } so here we're altering the widths of the columns and removing the float of the third column (and adding clearing to guard against any float funny business). we've also altered the width of the images inside the third container (no longer a column — this is the gallery) so that now you get five per line (it was previously three per l...
stitchTiles - SVG: Scalable Vector Graphics
idth="100" height="100" style="filter: url(#noise2); transform: translate(320px, 100px);" /> </svg> usage notes value nostitch | stitch default value nostitch animatable yes nostitch this value indicates that no attempt is made to achieve smooth transitions at the border of tiles which contain a turbulence function. sometimes the result will show clear discontinuities at the tile borders. stitch this value indicates that the user agent will automatically adjust the x and y values of the base frequency such that the <feturbulence> node’s width and height (i.e., the width and height of the current subregion) contain an integral number of the tile width and height for the first octave. specifications specification status comm...
systemLanguage - SVG: Scalable Vector Graphics
ri and english versions, would call for: <text systemlanguage="mi, en"><!-- content goes here --></text> however, just because multiple languages are present within the object on which the systemlanguage test attribute is placed, this does not mean that it is intended for multiple linguistic audiences. an example would be a beginner's language primer, such as "a first lesson in latin," which is clearly intended to be used by an english-literate audience. in this case, the attribute should only include en. specifications specification status comment scalable vector graphics (svg) 2the definition of 'systemlanguage' in that specification. candidate recommendation no change scalable vector graphics (svg) 1.1 (second edition)the definition of 'systemla...
<feComposite> - SVG: Scalable Vector Graphics
the first set wipes out the background image by flooding with opaque white. the second set does not wipe out the background, with the result that the background sometimes shines through and is other cases is blended into itself (i.e., "do...
Example - SVG: Scalable Vector Graphics
and above. view the example <?xml version='1.0'?> <html xmlns="http://www.w3.org/1999/xhtml" xmlns:svg="http://www.w3.org/2000/svg"> <head> <title>a swarm of motes</title> <style type='text/css'> <![cdata[ label, input { width: 150px; display: block; float: left; margin-bottom: 10px; } label { text-align: right; width: 75px; padding-right: 20px; } br { clear: left; } ]]> </style> </head> <body onload='update()'> <svg:svg id='display' width='400' height='300'> <svg:circle id='cursor' cx='200' cy='150' r='7' fill='#0000ff' fill-opacity='0.5'/> </svg:svg> <p>a swarm of motes, governed by two simple principles. first, each mote tries to move towards the cursor, and second each mote tries to move away from the average mote position. ...
Mixed content - Web security
pages like this are only partially encrypted, leaving the unencrypted content accessible to sniffers and man-in-the-middle attackers. that leaves the pages unsafe. ...
Transport Layer Security - Web security
ameters, which can have a substantial impact on the security and reliability of data. this article provides an overview of tls and the kinds of decisions you need to make when securing your content. history when https was introduced, it was based on secure sockets layer (ssl) 2.0, a technology introduced by netscape. it was updated to ssl 3.0 not long after, and as its usage expanded, it became clear that a common, standard encryption technology needed to be specified to ensure interoperability among all web browsers and servers. the internet engineering task force (ietf) specified tls 1.0 in rfc 2246 in january, 1999. the current version of tls is 1.3 (rfc 8446). despite the fact that the web now uses tls for encryption, many people still refer to it as "ssl" out of habit. although tls c...
Web security
sed using https. certificate transparency certificate transparency is an open framework designed to protect against and monitor for certificate misissuances. newly issued certificates are 'logged' to publicly run, often independent ct logs which maintain an append-only, cryptographically assured record of issued tls certificates. mixed content an https page that includes content fetched using cleartext http is called a mixed content page. pages like this are only partially encrypted, leaving the unencrypted content accessible to sniffers and man-in-the-middle attackers. how to fix a website with blocked mixed content if your website delivers https pages, all active mixed content delivered via http on these pages will be blocked by default. consequently, your website may appear broken to u...
Using templates and slots - Web Components
avoid the small trouble of needing to first access the template element's content property (and clone it). however, it is generally more practical to add slots within a <template> element, since you are unlikely to need to define a pattern based on an already-rendered element. in addition, even if it is not already rendered, the purpose of the container as a template should be more semantically clear when using the <template>. in addition, <template> can have items directly added to it, like <td>, which would disappear when added to a <div>. note: you can find this complete example at element-details (see it running live also). creating a template with some slots first of all, we use the <slot> element within a <template> element to create a new "element-details-template" document fragme...
Advanced Example - XSLT: Extensible Stylesheet Language Transformations
// set the sorting parameter in the xsl file var sortval = xsltprocessor.getparameter(null, "myorder"); if (sortval == "" || sortval == "descending") xsltprocessor.setparameter(null, "myorder", "ascending"); else xsltprocessor.setparameter(null, "myorder", "descending"); // initiate the transformation var fragment = xsltprocessor.transformtofragment(xmlref, document); // clear the contents document.getelementbyid("example").innerhtml = ""; mydom = fragment; // add the new content from the transformation document.getelementbyid("example").appendchild(fragment) } // xsl stylesheet: <?xml version="1.0" encoding="utf-8"?> <xsl:stylesheet version="1.0" xmlns="http://www.w3.org/1999/xhtml" xmlns:html="http://www.w3.org/1999/xhtml" xmlns:xsl="http://www.w3.org/1999...
Exported WebAssembly functions - WebAssembly
ction exported from a wasm module instance via instance.exports. either way, you get the same kind of wrapper for the underlying function. from a javascript point of view, it's as if every wasm function is a javascript function too — but they are encapsulated by the exported wasm function object instance and there are only limited ways to access them. ...
Using the WebAssembly JavaScript API - WebAssembly
memories can be defined inside a module or imported. similarly, a module may also optionally export its memory. this means that javascript can get access to the memory of a webassembly instance either by creating a new webassembly.memory and passing it in as an import or by receiving 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. note: you can see the module’s text representation at memory.wat. go back to your memory.html s...